【发布时间】:2016-02-01 12:29:22
【问题描述】:
我正在尝试从表中选择最佳 ID 并插入变量(可以是 int 或 long)。我的代码有点工作,但它没有得到它应该得到的数字。相反,它一直是 -1。
Ps1 - RXRX 是 ID 列。
Ps3 - 我已经尝试将 ExecuteNonQuery 替换为 ExecuteReader,但我收到以下错误:无法将类型 System.Data.SqlClient.SqlDataReader 隐式转换为 int
private int aux;
if(some condition)
{
MessageBox.Show("Should get a positive number in the next messageBox");
cmd.CommandText = "SELECT MAX(RXRX) from tablee";
aux = cmd.ExecuteNonQuery();
MessageBox.Show(aux.ToString()); //Gets -1 all the time
}
怎么了?遗憾的是,我不能使用 LAST INSERT ID 命令,因为该人可以在插入任何数据之前进入此 IF。
更新:得到答案。现在它正在工作,谢谢大家:
if(some condition)
{
MessageBox.Show("Should get a positive number in the next messageBox");
cmd.CommandText = "SELECT MAX(RXRX) from tablee";
aux = Convert.ToInt32(cmd.ExecuteScalar()); //Thanks Joachim Isaksson
MessageBox.Show(auxiliar.ToString()); //Now it works fine
}
【问题讨论】:
-
cmd.ExecuteScalar()怎么样? -
我之前尝试过,但有些东西不允许。我收到消息:“无法将类型 '' 隐式转换为 'int'。存在显式转换(您是否缺少演员表?)”