Connect to an #Oracle #Database from C#
Connecting to an Oracle Database in c# is just as easy as MySQL or SQL server, it just requires it’s own library and a different connection string.
First, you need the following Nuget Package
Install-Package Oracle.ManagedDataAccess
Then import it using:
using Oracle.ManagedDataAccess.Client;
Here’s a code example –
public static DataTable PopulateDataTable(string command)
{
var sqlConnection = @”Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=XE)));user id=system;Password=xyz123″;
var adapter = new OracleDataAdapter(command, sqlConnection) { SelectCommand = { CommandTimeout = 0 } };
var dataSet = new DataSet();
adapter.Fill(dataSet, “sql”);
return dataSet.Tables[“sql”];
}
Here, the default service is “XE”, the TNS port is 1521, theĀ username is system, and password is xyx123 – and the oracle server is on the same PC (localhost)
It’s used as follows;
var strSQL = “select * from someTable”;
var dt = PopulateDataTable(strSQL);
foreach(var dr in dt.Rows.Cast<DataRow>())
{
Console.WriteLine(dr[“someColumn”].ToString());
}
And if you are using AWS RDS, then the connection string will look like this:
Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=xxxxx.cwqutyyydm8x.eu-west-1.rds.amazonaws.com)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=ORCL)));user id=xxxxx;Password=xxxxxx
LikeLike