字符串后的未闭合引号'

时间:2017-07-14 10:11:23

标签: c# asp.net datagridview

我正在以网络形式处理Datagrid工具。一世 添加了编辑按钮,但每当我更新数据时,我都会收到错误:

  

类型' System.Data.SqlClient.SqlException'的异常发生在

     

System.Data.dll但未在用户代码中处理

     

附加信息:字符后面的未闭合引号    string',Computer = System.Web.UI.WebControls.TextBox其中rollno = 1'。

及以下是我在DataGrid的UpdateCommand Event中编写的代码

TextBox txtName = (TextBox)e.Item.Cells[1].Controls[0];
TextBox txtEnglish = (TextBox)e.Item.Cells[2].Controls[0];
TextBox txtComputer = (TextBox)e.Item.Cells[3].Controls[0];
string strSQL = "update student set Name='" + txtName.Text + "',English=" + txtEnglish + "',Computer=" + txtComputer + " where rollno=" + DataGrid1.DataKeys[e.Item.ItemIndex].ToString();
SqlCommand mycmd = new SqlCommand(strSQL, mycon);
mycon.Open();
mycmd.ExecuteNonQuery();
mycon.Close();
DataGrid1.EditItemIndex = -1;
FullupGrid();

1 个答案:

答案 0 :(得分:1)

使用格式以避免语法错误:

TextBox txtName = (TextBox)e.Item.Cells[1].Controls[0];
TextBox txtEnglish = (TextBox)e.Item.Cells[2].Controls[0];
TextBox txtComputer = (TextBox)e.Item.Cells[3].Controls[0];

string strSQL = 
  //DONE: Make SQL readable with a help of string interpolation and verbatim strings  
  $@"update Student 
        set Name     = '{txtName.Text}',
            English  = '{txtEnglish}',
            Computer = '{txtComputer}' 
      where RollNo   = {DataGrid1.DataKeys[e.Item.ItemIndex].ToString()}";

using (SqlConnection con = new SqlConnection("ConnectionStringHere")) {
  con.Open();

  using (SqlCommand mycmd = new SqlCommand(strSQL, con)) {
     mycmd.ExecuteNonQuery();
  }
}

DataGrid1.EditItemIndex = -1;
FullupGrid();

然而,更好的方法是参数化查询:

TextBox txtName = (TextBox)e.Item.Cells[1].Controls[0];
TextBox txtEnglish = (TextBox)e.Item.Cells[2].Controls[0];
TextBox txtComputer = (TextBox)e.Item.Cells[3].Controls[0];

string strSQL = 
  $@"update Student 
        set Name     = :prm_Name,
            English  = :prm_English,
            Computer = :prm_Computer 
      where RollNo   = :prm_RollNo";

using (SqlConnection con = new SqlConnection("ConnectionStringHere")) {
  con.Open();

  using (SqlCommand mycmd = new SqlCommand(strSQL, con)) {
    //TODO: a better choice is to create parameter with specified RDMBS type
    mycmd.Parameters.AddWithValue(":prm_Name", txtName.Text);         
    mycmd.Parameters.AddWithValue(":prm_English", txtEnglish);         
    mycmd.Parameters.AddWithValue(":prm_Computer", txtComputer);         
    mycmd.Parameters.AddWithValue(":prm_RollNo", 
      DataGrid1.DataKeys[e.Item.ItemIndex].ToString());         

    mycmd.ExecuteNonQuery();
  }
}

DataGrid1.EditItemIndex = -1;
FullupGrid();