单击时,我使用按钮将产品添加到数据库。这是我编写的代码,但它创建了一个未处理的异常。请帮我纠正一下......
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();
}
答案 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中测试它需要括号)