这行得通,但仍然容易受到注射的侵害吧?
是的,您的代码非常容易受到SQL注入的攻击。
我知道我应该使用参数化查询来避免SQL注入。
哦,是的。
我的问题是,当我将查询作为字符串参数传递时,该怎么办?
您根本不应该将查询作为字符串参数传递。相反,您应该将查询作为包含占位符和这些占位符值的字符串参数传递:
public static DataTable SqlDataTable(string sql, IDictionary<string, object> values){ using (SqlConnection conn = new SqlConnection(DatabaseConnectionString)) using (SqlCommand cmd = conn.CreateCommand()) { conn.Open(); cmd.CommandText = sql; foreach (KeyValuePair<string, object> item in values) { cmd.Parameters.AddWithValue("@" + item.Key, item.Value); } DataTable table = new DataTable(); using (var reader = cmd.ExecuteReader()) { table.Load(reader); return table; } }}然后像这样使用您的函数:
DataTable dt = SqlComm.SqlDataTable( "SELECt * FROM Users WHERe UserName = @UserName AND Password = @Password", new Dictionary<string, object> { { "UserName", login.Text }, { "Password", password.Text }, });if (dt.Rows.Count > 0){ // do something if the query returns rows}


