关于GridView防止用户SQL注入的方法
//下面是我写的一个关于GridView的例子;int rid = Convert.ToInt32(this.GridView1.DataKeys[e.RowIndex].Value.ToString());string rtitle = ((TextBox)(this.GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text;string rauthor = ((TextBox)(this.GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text;string rtime = ((TextBox)(this.GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text;//我写的一条sql执行语句,里面的rid 、rtitle 、rauthor 、rtime 是从GridView控件里面获取的,string sqlCon = "update news set ntitle='" + rtitle + "',nauthor='" + rauthor + "',ntime='" + rtime + "' where nid=" + rid;//如果用户在rtitle输入 '--' 的话就变成[code=SQL]update news set ntitle=''--'',nauthor='--',ntime='2007/8/15 0:00:00' where nid=31//这样的话数据库就彻底崩溃了
//现在我把他改成调用存储过程的方式来修改,
int rid = Convert.ToInt32(this.GridView1.DataKeys[e.RowIndex].Value.ToString());
string rtitle = ((TextBox)(this.GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text;
string rauthor = ((TextBox)(this.GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text;
string rtime = ((TextBox)(this.GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text;
using (SqlConnection con = new SqlConnection(conStr))
{
string procName = "proc_updatenews";
SqlCommand com = new SqlCommand(procName, con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@rid", rid);
com.Parameters.AddWithValue("@rtitle", rtitle);
com.Parameters.AddWithValue("@rauthor", rauthor);
com.Parameters.AddWithValue("@rtime", rtime);
con.Open();
result = com.ExecuteNonQuery();
}
//这样执行的结果却是好的。。
int rid = Convert.ToInt32(this.GridView1.DataKeys[e.RowIndex].Value.ToString());
string rtitle = ((TextBox)(this.GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text;
string rauthor = ((TextBox)(this.GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text;
string rtime = ((TextBox)(this.GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text;
using (SqlConnection con = new SqlConnection(conStr))
{
string procName = "proc_updatenews";
SqlCommand com = new SqlCommand(procName, con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@rid", rid);
com.Parameters.AddWithValue("@rtitle", rtitle);
com.Parameters.AddWithValue("@rauthor", rauthor);
com.Parameters.AddWithValue("@rtime", rtime);
con.Open();
result = com.ExecuteNonQuery();
}
//这样执行的结果却是好的。。
浙公网安备 33010602011771号