这是我的代码,它显示了此异常:
类型为'System.Data.SqlClient.SqlException'的未处理异常 发生在System.Data.dll“ ID”附近的语法不正确。
请使用以下代码帮助我:
public void count_accno()
{
conn.Open();
string str = "SELECT MAX(Category ID) FROM Category";
SqlCommand cmd = new SqlCommand(str, conn);
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
textBox1.Text = dr.GetValue(0).ToString();
}
int i = int.Parse(textBox1.Text);
i= i + 1;
textBox1.Text = i.ToString();
conn.Close();
dr.Close();
}
答案 0 :(得分:0)
好吧,Category ID
不是有效标识符,所以您有例外。在这里,我们提供三种典型的更正供您选择:
Category ID
,并输入正确的版本,例如Category_ID
,CategoryID
Category ID
,并具有有效的名称,并带有 space :[Category ID]
SELECT Max(Category), Max(ID) FROM Category
代码:
public void count_accno() {
//TODO: instead of opening existing connection, create a new one
conn.Open();
try {
string str =
@"SELECT MAX([Category ID]) -- wild guess: escapement
FROM Category";
//DONE: wrap IDisposable into using
using (SqlCommand cmd = new SqlCommand(str, conn)) {
//TODO: Have a look at ExecuteScalar
using (SqlDataReader dr = cmd.ExecuteReader()) {
//DONE: we want 1st record only (while is not wanted here)
// The query will return 1 record;
// thus we, probably want to check for `Null` not for `dr.Read`:
if (dr.Read() && !dr.IsDBNull(0)) {
textBox1.Text = (Convert.ToInt32(dr[0]) + 1).ToString();
}
else {
// Table is empty
}
}
}
}
finally {
// finally: rain or shine close the connection
conn.Close();
}
}
答案 1 :(得分:0)
MAX
函数需要1个参数。
您正在使用两个参数调用MAX:Category
和ID
。