This article describes the process of C # connecting to an Oracle database. With Oracle.DataAccess.dll in Instant client and odp.net, we can easily deploy. NET applications or sites without having to install Oracle clients. Next we'll introduce the process.
1. Installation of ODAC
Download the ODAC of the Oracle counterpart you installed on the official Oracle website.
Download Address: Odac Download
After downloading, unzip the installation, install without installing all the components. The following components are mainly installed:
Oracle Instant Client
Oracle Data Provider for. net2.0
Oracle rovider for ASP. Net
2. Setting of environment variable
To set Windows environment variables:
ORACLE_HOME:ODAC installation directory (similar to ~\app\administrator\product\11.1.0\client_1);
Ld_library_path:%oracle_home%;
Tns_admin:%oracle_home%;
Append at the front of path:%oracle_home%;
3. Monitor the configuration of file Tnsnames.ora
Under Directory%oracle_home%, create a new file Tnsnames.ora, which reads as follows:
Copy Code code 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
Once this is configured, Plsqldev can connect to the Oracle database.
5. C # connecting Oracle
The example code for C # connecting Oracle is as follows:
Copy Code code 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 configuration of the database connection in the program app.config or web.config.
Copy Code code 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 the steps above, and if there are no errors, you can successfully connect to the database.