关于防止SQL注入攻击
初学asp.net,刚写了一段查询数据库的代码,写的过程中碰到不少问题,多亏有CSDN高手指点,现在终归是可以运行了。我想请教的是,如何优化代码,变的更高效,安全。还请高手指点。代码如下:
protected void Button1_Click1(object sender, EventArgs e)
{
this.Title="查询货物状态";
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);
sqlcon.Open();
string str_state="";
if (TextBox1.Text == "")
{
Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<Script language='javascript' defer>alert('请输入订单号!');</Script>");
}
else
{
string tex1 = string.Format("SELECT COUNT(*) FROM 状态表 WHERE 订单号='{0}'", TextBox1.Text.Trim());
SqlCommand myComand = new SqlCommand(tex1, sqlcon);
int count = (int)myComand.ExecuteScalar();
if (count <= 0)
{
Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<Script language='javascript' defer>alert('订单号有误!');</Script>");
}
else
{
str_state = "SELECT * FROM 状态表 WHERE 订单号=" + TextBox1.Text;
SqlDataAdapter sqlda = new SqlDataAdapter(str_state, sqlcon);
DataSet ds = new DataSet(); //声明一个dataset对象
sqlda.Fill(ds,"状态表");
GridView1.DataSource = ds;
GridView1.DataBind(); //绑定数据记录
sqlcon.Close();
}
}
}