我有异常错误“ System.Data.dll的'ID'附近的语法不正确,发生了'System.Data.SqlClient.SqlException类型的未处理的异常”。

时间:2019-12-13 10:12:00

标签: c# sql .net

这是我的代码,它显示了此异常:

  

类型为'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();
   }

2 个答案:

答案 0 :(得分:0)

好吧,Category ID不是有效标识符,所以您有例外。在这里,我们提供三种典型的更正供您选择:

  1. 验证字段名称Category ID,并输入正确的版本,例如Category_IDCategoryID
  2. 转义Category ID,并具有有效的名称,并带有 space [Category ID]
  3. 具有两个字段: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:CategoryID