My C#.NET application needs to read from an Oracle database. There are many elaborate ways to connect to a database in .NET, including the Linq for Entities ORM. However, this was way too much for my purpose. I’ve found the following code to be much simpler. It’s largely copied from a C# Station post. The key difference is that you have to use the OracleClient class.
First: Make sure that your project has a reference to System.Data.OracleClient
string connectionString = @"
SERVER=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP
(HOST=OracleHost)(PORT=OraclePort))
(CONNECT_DATA=(SERVICE_NAME=OracleServiceName)))
;uid=UserID;pwd=Password;";
OracleConnection conn = new
OracleConnection(connectionString);
OracleDataReader rdr = null;
try
{
// 2. Open the connection
conn.Open();
// 3. Pass the connection to a command object
OracleCommand cmd = new OracleCommand(
"select * from mytable", conn);
//
// 4. Use the connection
//
// get query results
rdr = cmd.ExecuteReader();
// print each record
while (rdr.Read())
{
for ( int i = 0;
iConsole.WriteLine(rdr[i]);
// Print each field
}
}
catch
{
throw;
}
finally
{
// close the reader
if (rdr != null)
{
rdr.Close();
}
// 5. Close the connection
if (conn != null)
{
conn.Close();
}
} // End of try-catch-finally
Thanks are also due to ConnectionStrings.com