从oracle数据库中检索C#中的值

时间:2011-07-18 10:01:28

标签: c#

我不知道为什么但是我在尝试从oracle数据库中的表中获取最大整数值时遇到错误:这是代码:

string oradb = "Data Source=";
            oradb = oradb + Login.db + ";";
            oradb = oradb + "User Id=" + Login.user;
            oradb = oradb + ";Password=" + Login.pass + ";";
            OracleConnection conn = new OracleConnection(oradb);
            conn.Open();
            string term = GetTerminal(terminal);
            string sql = "SELECT tallynumber from "+frmSchemas.schema + ".tallies" ;
             MessageBox.Show(sql);
            OracleCommand cmd = new OracleCommand(sql, conn);
            cmd.CommandType = CommandType.Text;
            OracleDataReader dr = cmd.ExecuteReader();
            MessageBox.Show("1");
            Int64 TallyNo = dr.GetInt32(0);  



      // lblTallyNo.Text = (TallyNo).ToString()

返回的值应为:72332(如果有任何相关性)

3 个答案:

答案 0 :(得分:1)

如果您想从max value找到tablequery应为

SELECT max(tallynumber) from ....

如果您想获得max, min etc值,则应拨打ExecuteScalar()而不是ExecuteReader().

所以你的代码可以变成

   string sql = "SELECT Max(tallynumber) from "+frmSchemas.schema + ".tallies";              MessageBox.Show(sql);             
    OracleCommand cmd = new OracleCommand(sql, conn);             
    cmd.CommandType = CommandType.Text;             
    object val = cmd.ExecuteScalar();
int res = int.MinValue;             
    //MessageBox.Show("1");
  if(int.TryParse(val.ToString(), out res)) 
    Int64 TallyNo = res;

答案 1 :(得分:1)

在访问值之前,您缺少dr.Read();

OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
Int64 TallyNo = dr.GetInt32(0);

答案 2 :(得分:1)

您可以尝试使用以下

        string sql = "SELECT max(tallynumber) from "+frmSchemas.schema + ".tallies" ;
         MessageBox.Show(sql);
        OracleCommand cmd = new OracleCommand(sql, conn);
        cmd.CommandType = CommandType.Text;
        OracleDataReader dr = cmd.ExecuteReader();
        MessageBox.Show("1");
        if (dr.Read())
        {
        Int64 TallyNo = dr.GetInt32(0); 
        }

编辑:

if(dr.Read())
{
Int64 TallyNo = Convert.ToInt64(dr["tallynumber"].ToString());
}