您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

参数化查询与SQL注入

参数化查询与SQL注入

这行得通,但仍然容易受到注射的侵害吧?

是的,您的代码非常容易受到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
}
SQLServer 2022/1/1 18:17:19 有590人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶