c#通过oledb连接Oracle代码

rt
2024-12-21 21:28:22
推荐回答(2个)
回答1:

先装oracle客户端
1、控制面板->管理工具->数据源(ODBC)->添加数据源->选择oracle 客户端
Data Source Name 可以任意起名,推荐和SID一样
Description 描述
TNS Service Name 下拉菜单中会自动显示环境变量TNS_ADMIN所指目录下的tnsnames.ora文件中SERVICE_NAME的名称,也就是要连接的SID UserID 用户名
2、代码
string ConnectionString = "Data Source=orcl; User Id=SCOTT; Password=scott"; //连接字符串
OracleConnection conn = new OracleConnection(ConnectionString); //创建一个新连接

try
{
conn.Open(); //打开连接
OracleCommand cmd = conn.CreateCommand();

cmd.CommandText = "select * from emp"; //SQL语句
OracleDataReader rs = cmd.ExecuteReader();

while (rs.Read()) //读取数据,如果rs.Read()返回为false的话,就说明到记录集的尾部了
{
MessageBox.Show(rs.GetString(1));
}

rs.Close();
}

catch (Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
conn.Close();
}

回答2:

Oracle
ODBC

New version:
"Driver={Microsoft ODBC for Oracle};Server=OracleServer.world;Uid=Username;Pwd=asdasd;"

Old version:
"Driver={Microsoft ODBC Driver for Oracle};ConnectString=OracleServer.world;Uid=myUsername;Pwd=myPassword;"

OLEDB, OleDbConnection (.NET)

Standard security:
"Provider=msdaora;Data Source=MyOracleDB;User Id=UserName;Password=asdasd;"
This one's from Microsoft, the following are from Oracle
Standard Security:
"Provider=OraOLEDB.Oracle;Data Source=MyOracleDB;User Id=Username;Password=asdasd;"

Trusted Connection:
"Provider=OraOLEDB.Oracle;Data Source=MyOracleDB;OSAuthent=1;"

OracleConnection (.NET)

Standard:
"Data Source=Oracle8i;Integrated Security=yes";
This one works only with Oracle 8i release 3 or later
Declare the OracleConnection:

C#:
using System.Data.OracleClient;
OracleConnection oOracleConn = new OracleConnection();
oOracleConn.ConnectionString = "my connectionstring";
oOracleConn.Open();

VB.NET:
Imports System.Data.OracleClient
Dim oOracleConn As OracleConnection = New OracleConnection()
oOracleConn.ConnectionString = "my connectionstring"
oOracleConn.Open()

Data Shape

MS Data Shape:
"Provider=MSDataShape.1;Persist Security Info=False;Data Provider=MSDAORA;Data Source=orac;user id=username;password=mypw"