我正在使用以下代码连接到oracle服务器。我需要特别使用OdbcConnection类,因为我正在对现有应用程序进行增强,该应用程序当前正在使用此方法连接到SQL Server。因此,我还必须对其他DBMS使用相同的方法。
我尝试使用以下代码:
const string ConnectionString = @"SERVER=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=MachineName.Domain.com)(PORT=1521))(CONNECT_DATA=(SERVER = DEDICATED)(SERVICE_NAME=orcl.Domain.com)));uid=system;pwd=user";
using (OdbcConnection connection = new OdbcConnection(ConnectionString))
{
connection.Open();
}
但是在调用Open()方法时出现异常:
“错误[IM002] [Microsoft] [ODBC驱动程序管理器]数据源名称未找到,未指定默认驱动程序”
有什么想法我在这里做错了吗?
答案 0 :(得分:0)
您的connectionString应该像这样:
var DB = @"SERVER=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=MachineName.Domain.com)(PORT=1521))(CONNECT_DATA=(SERVER = DEDICATED)(SERVICE_NAME=orcl.Domain.com)))";
string ConnectionString = "Driver={Oracle in OraClient11g_home1};Dbq=" + DB + ";uid=system;pwd=user;"
您的计算机上的驱动程序名称可能不同。您也可以使用Microsoft(Driver={Microsoft ODBC for Oracle};Server=...
)的ODBC驱动程序,但是不推荐使用它。
实际上,我更喜欢DbConnectionStringBuilder(甚至是OdbcConnectionStringBuilder
)
var str = new DbConnectionStringBuilder(true);
str.Add("Driver", "Oracle in OraClient11g_home1");
str.Add("Dbq", @"(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=MachineName.Domain.com)(PORT=1521))(CONNECT_DATA=(SERVER = DEDICATED)(SERVICE_NAME=orcl.Domain.com)))");
str.Add("Uid", "system");
str.Add("Pwd", "user");
string ConnectionString = str.ConnectionString;
答案 1 :(得分:0)
///Your connection string should be like
string str = Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = abc )(PORT = 123))(CONNECT_DATA =(SID = xyz)));User Id=abc_xyz;Password=111;Min Pool Size=10;Connection Lifetime=120;Connection Timeout=600;Incr Pool Size=5; Decr Pool Size=2;validate connection=true;
using (OracleConnection con = new OracleConnection(str))
{
using (OracleCommand cmd = con.CreateCommand())
{
if (con.State != ConnectionState.Open)
{
con.Open();
}
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = RoutineConstant.Text;
cmd.BindByName = true;
cmd.ExecuteNonQuery();
if (cmd.Parameters["Value"].Value != null && cmd.Parameters["Value"].Value != DBNull.Value)
{
return Convert.ToDecimal(cmd.Parameters["Value"].Value.ToString());
}
}
}