how to connect to oracle in csharp

To connect to Oracle database in C#, we need to use ADO.NET which is an API for interacting with relational databases. ADO.NET provides a class called OracleConnection which is used for establishing a connection with the Oracle database. Here is an example code:

main.cs
using System.Data.OracleClient;

class Program {
    static void Main() {
        string connectionString = "Data Source=YOUR_DATA_SOURCE; User ID=YOUR_USERNAME; Password=YOUR_PASSWORD;";
        OracleConnection conn = new OracleConnection(connectionString);
        try {
            conn.Open();
            Console.WriteLine("Connection to Oracle successful!");
        } catch (Exception ex) {
            Console.WriteLine("Failed to connect to Oracle: " + ex.Message);
        } finally {
            conn.Close();
        }
    }
}
540 chars
17 lines

In the code above, we first import the System.Data.OracleClient namespace. Then, we define a connectionString that contains the authentication information of the database. After that, we create a OracleConnection object and pass the connectionString as the parameter to the constructor.

We then call the Open() method to open the connection to the database. If an exception occurs, we catch the exception and display the error message. Finally, we close the connection by calling the Close() method.

Note that in recent versions of .NET Framework, OracleConnection and other Oracle data access classes have been deprecated. In this case, you can use a third-party library like ODP.NET (Oracle Data Provider for .NET) to connect to your Oracle database.

gistlibby LogSnag