C# 字符串';
我正在以web形式开发Datagrid工具。我 添加了“编辑”按钮,但每当我更新数据时,都会出现错误: 中发生类型为“System.Data.SqlClient.SqlException”的异常 System.Data.dll,但未在用户代码中处理 附加信息:字符后未闭合的引号 字符串',Computer=System.Web.UI.WebControls.TextBox,其中rollno=1' 下面是我在DataGrid的UpdateCommand事件中编写的代码C# 字符串';,c#,asp.net,datagridview,C#,Asp.net,Datagridview,我正在以web形式开发Datagrid工具。我 添加了“编辑”按钮,但每当我更新数据时,都会出现错误: 中发生类型为“System.Data.SqlClient.SqlException”的异常 System.Data.dll,但未在用户代码中处理 附加信息:字符后未闭合的引号 字符串',Computer=System.Web.UI.WebControls.TextBox,其中rollno=1' 下面是我在DataGrid的UpdateCommand事件中编写的代码 TextBox txtNam
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();
使用格式设置以避免语法错误:
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();
您应该使用参数化查询。这可以防止SQL注入和此类错误。当然!您确实使用了
English=“+txtEnglish+”,
,但它应该是English='“+txtEnglish+”,