用c#从oracle数据库中检索值
本文关键字:检索 数据库 oracle | 更新日期: 2023-09-27 18:02:29
我不知道为什么,但我得到一个错误,试图从一个表在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
您可以尝试使用以下
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());
}
在访问值
之前缺少一个dr.Read();
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
Int64 TallyNo = dr.GetInt32(0);
如果你想从一个table
中找到max value
,那么query
应该是
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;