如何使用asp.net c#中的类,方法,参数为此语句传递SQL语句。 首先,我想创建一个方法并为调用值添加参数。
protected void Btnsubmit_Click(object sender, EventArgs e)
{
String Orders = "INSERT INTO Orders VALUES('" + DDLCustomerID.SelectedValue + "','" + Convert.ToInt32(TxtNetPrice.Text) + "');" + " SELECT SCOPE_IDENTITY();";
using (SqlCommand command = new SqlCommand(Orders, Connection))
{
command.CommandType = CommandType.Text;
Connection.Open();
int intID = Convert.ToInt32(command.ExecuteScalar());
String Orderdetails1 = "INSERT INTO OrderDetails VALUES(" + intID + ",'" + DDLProduct1.SelectedItem + "','" + Convert.ToInt32(TxtPrice1.Text) + "','" + Convert.ToInt32(TxtQuantity1.Text) + "','" + Convert.ToInt32(TxtTotalPrice1.Text) + "')";
SqlCommand Command1 = new SqlCommand(Orderdetails1, Connection);
Command1.CommandType = CommandType.Text;
Command1.ExecuteNonQuery();
String Orderdetails2 = "INSERT INTO OrderDetails VALUES(" + intID + ",'" + DDLProduct2.SelectedItem + " ','" + Convert.ToInt32(TxtPrice2.Text) + "','" + Convert.ToInt32(TxtQuantity2.Text) + "','" + Convert.ToInt32(TxtTotalPrice2.Text) + "')";
SqlCommand Command2 = new SqlCommand(Orderdetails2, Connection);
Command2.CommandType = CommandType.Text;
Command2.ExecuteNonQuery();
String Orderdetails3 = "INSERT INTO OrderDetails VALUES(" + intID + ",'" + DDLProduct3.SelectedItem + " ','" + Convert.ToInt32(TxtPrice3.Text) + "','" + Convert.ToInt32(TxtQuantity3.Text) + "','" + Convert.ToInt32(TxtTotalPrice3.Text) + "')";
SqlCommand Command3 = new SqlCommand(Orderdetails3, Connection);
Command3.CommandType = CommandType.Text;
Command3.ExecuteNonQuery();
Response.Write("<script>alert('Successfully Inserted');</script>");
Connection.Close();
}
}
答案 0 :(得分:0)
最好使用存储过程并在事务中执行插入操作。内联查询总是有风险,并且对sql注入开放。
答案 1 :(得分:0)
正如您的问题建议您绝对必须使用参数化查询,以避免SQL注入。您的代码直接容易受此影响我认为您在查询字符串中包含DDLProduct1.SelectedItem
的位置。如果您已经知道这一点,请道歉 - 对于未来登陆此问题的其他人来说,值得明确:o)
要使用SqlCommand
参数化查询,您需要使用SqlCommand.Parameters
属性:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters(v=vs.110).aspx
替代方法是使用良好的ORM,例如实体框架。这为您的查询设置了参数,因此不存在遗忘的危险。如果您使用谷歌,那么网上有很多很好的教程
如果您需要继续使用SqlCommand
,这就是您的操作方法(使用您的订单查询示例 - 其他类似):
string Orders = "INSERT INTO Orders VALUES(@customerID, @price); SELECT SCOPE_IDENTITY();";
SqlCommand command = new SqlCommand(Orders, Connection);
command.Parameters.Add("@customerID", SqlDbType.Int);
command.Parameters["@customerID"].Value = DDLCustomerID.SelectedValue;
command.Parameters.Add("@price", SqlDbType.Int);
command.Parameters["@price"].Value = Convert.ToInt32(TxtNetPrice.Text);
请注意,你需要一些错误处理转换 - 如果TxtNetPrice
无法转换为整数会发生什么?