如何查找ASP.net SQL插入查询中的错误



你好,我在下面的代码中使用asp.net在表中插入,我得到了这个错误System.Data.SqlClient.SqlException:','附近的语法不正确。'有人能帮我解决的问题吗

protected void ButtonSave_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=LAPTOP-U11A4VS6;Initial Catalog=Task;Integrated Security=True");
con.Open();
//SqlCommand cmd = new SqlCommand("Invoice_Product", con);
//cmd.CommandType = CommandType.StoredProcedure;
SqlCommand cmd = new SqlCommand("insert into [Invoice_Product] (" + Convert.ToInt32(TextBoxInvoice.Text)
+ "','"+Convert.ToInt32(TextBoxInvoice.Text)+"','"+"'"+TextBoxDate.Text+"'"
+ "','"+"'"+DropDownList1.SelectedItem.Text+"'"
+"','"+"'"+DropDownList2.SelectedItem.Text+"'"+"','"+Convert.ToDouble(LabelPrice1.Text) 
+ "','"+Convert.ToInt32(TextBoxQty.Text)+"','"+Convert.ToDouble(LabelTot1.Text)
+ "','"+Convert.ToDouble(LabelDiscount1.Text)+"','"+Convert.ToDouble(LabelNet1.Text)  
+ "','"+"'"+DropDownListStores.SelectedItem.Text+"'"+"','"+Convert.ToDouble(TextBoxFinalTot.Text)
+ "','"+Convert.ToDouble(TextBoxTaxes.Text)+ "','"+Convert.ToDouble(TextBoxFinalNet.Text)+")",con);
int k = cmd.ExecuteNonQuery();
if (k > 0)
{
Response.Write("<script> alert ('User Added')</Script>)");
}
else Response.Write("<script> alert ('Error')</Script>)");
//con.Close();
}                                                                                              

首先,学习如何在插入中使用参数绑定。您已暴露SQL注入。

发现语法错误的第一个实现是将查询放入字符串变量中,并在执行语句之前停止调试器。

您可以在SQL客户端中进行复制和粘贴。

重写代码的第一种方法。缺少一些专栏,仅供参考。检查底部的链接。

protected void ButtonSave_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=LAPTOP-U11A4VS6;Initial Catalog=Task;Integrated Security=True");
con.Open();
//SqlCommand cmd = new SqlCommand("Invoice_Product", con);
//cmd.CommandType = CommandType.StoredProcedure;
string sqlString = "INSERT INTO [Invoice_Product] VALUES (@FIELD1, @FIELD2)"
//put the breakpoint on next line and check the value of sqlString
SqlCommand cmd = new SqlCommand(sqlString,con);
cmd.Parameters.Add("@FIELD1", SqlDbType.Int);
cmd.Parameters["@FIELD1"].Value = TextBoxInvoice.Text;
cmd.Parameters.Add("@FIELD2", SqlDbType.DateTime);
cmd.Parameters["@FIELD2"].Value = TextBoxDate.Text;
int k = cmd.ExecuteNonQuery();
if (k > 0)
{
Response.Write("<script> alert ('User Added')</Script>)");
}
else 
Response.Write("<script> alert ('Error')</Script>)");
//con.Close();
}   

检查此链接https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.parameters?view=netframework-4.8

您的代码中有这样的东西:

"','"+"'"

将输出:

',''

所以你在某些地方把引号加倍了。


不过我要注意上面的评论,这确实不是构建查询的好方法。

最新更新