0

我想访问数据库列中的最后一个值,将其递增 1 并显示在我使用此代码的文本框中,但文本框中没有显示此代码有什么问题?

SqlCommand cmd = new SqlCommand("SELECT (MAX[Account_No]  FROM addcustomer ", my);

int result = ((int)cmd.ExecuteScalar());
textBox1.Text = result.ToString();
4

5 回答 5

2
SqlCommand cmd = new SqlCommand("SELECT MAX(Account_No)  FROM addcustomer ", my);
int result = ((int)cmd.ExecuteScalar()) + 1;
textBox1.Text = result.ToString();
于 2013-09-04T08:29:39.777 回答
1

您错误地放置了括号。改变这个

SqlCommand cmd = new SqlCommand("SELECT (MAX[Account_No]  FROM addcustomer ", my);

进入那个

SqlCommand cmd = new SqlCommand("SELECT MAX(Account_No)  FROM addcustomer ", my);
于 2013-09-04T08:30:13.267 回答
0

您可以如下更改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?
}
于 2013-09-04T08:51:46.220 回答
0

看起来你缺少一个括号:

SqlCommand cmd = new SqlCommand("SELECT (MAX[Account_No]  FROM addcustomer ", my);

应该

SqlCommand cmd = new SqlCommand("SELECT MAX(Account_No)  FROM addcustomer", my);
于 2013-09-04T08:28:34.547 回答
0
SqlCommand cmd = new SqlCommand("SELECT MAX(Account_No)  FROM addcustomer ", my);
于 2013-09-04T08:29:44.150 回答