This article describes how C # connects to the Oracle database. Through the Oracle. DataAccess. dll in instant client and ODP.net, We can conveniently deploy. net applications or sites without installing the Oracle client. Next we will introduce this process.
1. Install ODAC
Download the corresponding oracle version ODAC from the official oracle website.
: ODAC Download
Download the package and decompress the package. You do not need to install all the components during installation. Install the following components:
Oracle Instant Client
Oracle Data Provider For. net2.0
Oracle rovider For Asp. net
2. environment variable settings
Set Windows environment variables:
ORACLE_HOME: ODAC installation directory (similar ~ \ App \ Administrator \ product \ 11.1.0 \ client_1 );
LD_LIBRARY_PATH: % ORACLE_HOME %;
TNS_ADMIN: % ORACLE_HOME %;
Append at the beginning of PATH: % ORACLE_HOME %;
3. Configure tnsnames. ora in the listener File
Create the tnsnames. ora file in the directory % ORACLE_HOME %. The content is as follows:
Copy codeThe Code is as follows:
Database SID =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP) (HOST = Oracle HOST name or IP) (PORT = 1521 ))
)
(CONNECT_DATA =
(SERVICE_NAME = database SID)
)
)
4. plsqldev
After this configuration, plsqldev can connect to the oracle database.
5. C # connect to Oracle
C # sample code for connecting to oracle:
Copy codeThe Code is as follows:
OracleConnection conn =
New OracleConnection ();
Try
{
Conn. ConnectionString = ConfigurationManager. ConnectionStrings ["oradb"]. ConnectionString;
Conn. Open ();
String SQL = "select id, content from test"; // C #
OracleCommand cmd = new OracleCommand (SQL, conn );
Cmd. CommandType = CommandType. Text;
OracleDataReader dr = cmd. ExecuteReader (); // C #
List <string> contents = newList <string> ();
While (dr. Read ())
{
Contents. Add (dr ["content"]. ToString ());
}
ListBox1.ItemsSource = contents;
}
Catch (Exception ex)
{
MessageBox. Show (ex. Message );
}
Finally
{
Conn. Clone ();
}
Append the database connection configuration in app. config or web. config.
Copy codeThe Code is as follows:
<ConnectionStrings>
<Add name = "oradb" connectionString = "Data Source = (DESCRIPTION =
(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP) (HOST = 192.168.1.1) (PORT = 1521 )))
(CONNECT_DATA = (SERVICE_NAME = ****)));
User Id = ***; Password = ***; "/>
</ConnectionStrings>
Follow these steps to connect to the database successfully without errors.