【问题标题】:Unclosed quotation mark after the character string ' [duplicate]字符串 ' 后的非闭合引号 [重复]
【发布时间】:2017-12-19 09:37:54
【问题描述】:

我正在开发 Web 形式的 Datagrid 工具。一世 已添加编辑按钮,但每当我更新数据时,我都会收到错误消息:

发生了“System.Data.SqlClient.SqlException”类型的异常

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

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

下面是我在DataGrid的UpdateCommand事件中写的代码

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();

【问题讨论】:

  • 您应该使用参数化查询。这可以防止 SQL 注入和此类错误。
  • 当然!你做了English=" + txtEnglish + "',但它应该是English='" + txtEnglish + "',

标签: c# asp.net datagridview


【解决方案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();

【讨论】:

    猜你喜欢
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多