【问题标题】:Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near 'Programming'异常详细信息:System.Data.SqlClient.SqlException:“编程”附近的语法不正确
【发布时间】:2014-02-25 19:17:02
【问题描述】:

单击时,我正在使用一个按钮将产品添加到数据库中。这是我编写的代码,但它创建了一个未处理的异常。请帮我改正...

protected void Button1_Click(object sender, EventArgs e)
{
    string s = @"~\Images" + FileUpload1.FileName;
    FileUpload1.PostedFile.SaveAs(Server.MapPath(s));
    string ConStr = ConfigurationManager.ConnectionStrings["HoriZon"].ConnectionString;
    SqlConnection NewCon = new SqlConnection(ConStr);
    NewCon.Open();

    String cmd1 = "INSERT INTO Subjects(SubjectName, Description, ImagePath, UnitPrice, CategoryID) values('" + name.Text + "','" + description.Text + "','" + s + "', '" + price.Text + "', '" + "SELECT CategoryID FROM dbo.Categories WHERE CategoryName = '" + catText.Text + "'" +"')";
    SqlCommand b = new SqlCommand(cmd1, NewCon);

    b.ExecuteNonQuery();

    NewCon.Close();
}

【问题讨论】:

  • 你看到了什么异常?

标签: sql-server sql-server-2008 c#-4.0


【解决方案1】:

我建议使用参数化查询而不是字符串连接

String cmd1 = @"INSERT INTO Subjects(SubjectName, Description, ImagePath, UnitPrice, CategoryID) 
               values(@name, @desc, @img, @price, (SELECT CategoryID FROM dbo.Categories 
               WHERE CategoryName = @cname))";
SqlCommand b = new SqlCommand(cmd1, NewCon);
b.Parameters.AddWithValue("@name",name.Text );
b.Parameters.AddWithValue("@desc",description.Text );
b.Parameters.AddWithValue("@img",s);
b.Parameters.AddWithValue("@price",price.Text );
b.Parameters.AddWithValue("@cname",catText.Text);
b.ExecuteNonQuery();

另外,返回 CategoryID 的子查询应该用括号括起来(至少直接在 SSMS 中测试需要括号)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 2019-07-17
    • 2017-12-08
    • 2014-05-09
    • 2018-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多