TOP

[C#]SQL Parameter defense SQL injection

最容易被SQL injection 的語法如下:

SqlConnection conn = new SqlConnection("");
conn.ConnectionString =    System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
string sqlstr = "select * from table where name = '" + strName + "'";
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(sqlstr, conn);
conn.Close();
da.Dispose();

目前利用SQL Parameter 就可以避免此問題

SqlConnection conn = new SqlConnection("");
conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
string strSql = "select * from table where Name=@Name";
conn.Open();
SqlCommand sqlcom = new SqlCommand(strSql, conn);
sqlcom.Parameters.AddWithValue("@Name", strName );
SqlDataReader sqldr = sqlcom.ExecuteReader();
sqldr.Close();
conn.Close(); 



0 意見:

張貼留言