C#Oracle数据库连接

时间:2014-08-25 14:36:43

标签: c# oracle

我正在尝试使用C#连接到oracle数据库。

这是我的代码:

      OracleConnection conn = new OracleConnection(); // C#
           conn.ConnectionString = oradb;
        conn.Open();
        string sql = " select department_name from departments where department_id = 10"; // C#
        OracleCommand cmd = new OracleCommand();
        cmd.CommandText = sql;
        cmd.Connection = conn;
        cmd.CommandType = CommandType.Text; ///this is the line that gives the error

设置命令类型的正确方法是什么?谢谢。

2 个答案:

答案 0 :(得分:2)

使用存储过程

using (OracleConnection conn = new OracleConnection( oradb ))
{
      conn.Open();
      OracleCommand cmd = new OracleCommand("StoreProcedureName", con);
      cmd.CommandType = CommandType.StoredProcedure;   

      //specify command parameters 
      //and Direction

      using(OracleDataReader reader = cmd.ExecuteReader())
      {
          while (reader.Read())
          {
             //string s = reader.GetInt32(0) + ", " + reader.GetInt32(1);
          }
      }                   
}

CommandType.Text :(不是必须指定CommandType)。

using (OracleConnection conn = new OracleConnection( oradb ))
{
      string sql = @"SELECT department_name FROM departments 
                     WHERE department_id = @department_id";
      conn.Open();
      OracleCommand cmd = new OracleCommand(sql, conn);

      //specify command parameters
      cmd.Parameters.Add(new OracleParameter("@department_id", 10));

      using(OracleDataReader reader = cmd.ExecuteReader())
      {
          while (reader.Read())
          {
             //string s = reader.GetString(0);
          }
      }                   
}

答案 1 :(得分:1)

确保在using()语句中输入每个部分,即

using( OracleConnection conn = new OracleConnection( oradb ) )
{
    conn.Open();

    using( OracleCommand cmd = new OracleCommand( "sql here", conn ) )
    {
        //cmd.Execute(); cmd.ExecuteNonQuery();
    }
}