这行得通,但仍然容易受到注射的侵害吧?
哦,是的。
我的问题是,当我将查询作为字符串参数传递时,该怎么办?
您根本不应该将查询作为字符串参数传递。相反,您应该将查询作为包含占位符和这些占位符值的字符串参数传递:
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
}