我想访问数据库列中的最后一个值,将其递增 1 并显示在我使用此代码的文本框中,但文本框中没有显示此代码有什么问题?
SqlCommand cmd = new SqlCommand("SELECT (MAX[Account_No] FROM addcustomer ", my);
int result = ((int)cmd.ExecuteScalar());
textBox1.Text = result.ToString();
我想访问数据库列中的最后一个值,将其递增 1 并显示在我使用此代码的文本框中,但文本框中没有显示此代码有什么问题?
SqlCommand cmd = new SqlCommand("SELECT (MAX[Account_No] FROM addcustomer ", my);
int result = ((int)cmd.ExecuteScalar());
textBox1.Text = result.ToString();
SqlCommand cmd = new SqlCommand("SELECT MAX(Account_No) FROM addcustomer ", my);
int result = ((int)cmd.ExecuteScalar()) + 1;
textBox1.Text = result.ToString();
您错误地放置了括号。改变这个
SqlCommand cmd = new SqlCommand("SELECT (MAX[Account_No] FROM addcustomer ", my);
进入那个
SqlCommand cmd = new SqlCommand("SELECT MAX(Account_No) FROM addcustomer ", my);
您可以如下更改sql语句
SELECT MAX(Account_No) + 1 FROM addcustomer
或通过代码选择值后递增
SqlCommand cmd = new SqlCommand("SELECT MAX(Account_No) FROM addcustomer ", my);
int result = ((int)cmd.ExecuteScalar()) +1;
最终代码将是:
try
{
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand("SELECT MAX(Account_No) + 1 FROM addcustomer", con))
{
con.Open();
int result = (int)cmd.ExecuteScalar();
textBox1.Text = result.ToString();
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString()); // do you get any Exception here?
}
看起来你缺少一个括号:
SqlCommand cmd = new SqlCommand("SELECT (MAX[Account_No] FROM addcustomer ", my);
应该
SqlCommand cmd = new SqlCommand("SELECT MAX(Account_No) FROM addcustomer", my);
SqlCommand cmd = new SqlCommand("SELECT MAX(Account_No) FROM addcustomer ", my);