c# – 参数化查询与SQL注入

c# – 参数化查询与SQL注入,第1张

概述我是 Asp.net的新手,我刚刚开始上课.我最近创建了一个类,它将为我处理大多数SQL查询,这样我就不必重复创建所有文件的新连接. 我创建的方法之一将SQL查询作为参数并返回结果.我知道我应该使用参数化查询来避免SQL注入.我的问题是,当我将查询作为字符串参数传递时,我该怎么做? 例如,这是我将要调用的方法: public static DataTable SqlDataTable(string 我是 Asp.net的新手,我刚刚开始上课.我最近创建了一个类,它将为我处理大多数SQL查询,这样我就不必重复创建所有文件的新连接.

我创建的方法之一将SQL查询作为参数并返回结果.我知道我应该使用参数化查询来避免sql注入.我的问题是,当我将查询作为字符串参数传递时,我该怎么做?

例如,这是我将要调用的方法:

public static Datatable sqlDatatable(string sql){    using (sqlConnection conn = new sqlConnection(DatabaseConnectionString))    {        sqlCommand cmd = new sqlCommand(sql,conn);        cmd.Connection.open();        Datatable Temptable = new Datatable();        Temptable.Load(cmd.ExecuteReader());        return Temptable;    }}

所以我想从另一个文件中使用这个方法:

Datatable dt = new Datatable();dt = sqlComm.sqlDatatable("SELECT * FROM Users WHERE Username='" + login.Text  + "' and Password='" + password.Text + "'");if (dt.Rows.Count > 0){   // do something if the query returns rows}

这有效,但仍然容易受到注射吗?有没有办法可以将变量作为参数传递给字符串?我知道如果我为查询创建一个新的sqlCommand对象并使用Parameters.AdDWithValue,我可以这样做,但我希望所有的sql命令都在单独的类中.

解决方法

This works but would still be vulnerable to injections right?

是的,你的代码非常容易受到sql注入攻击.

I kNow that I should be using parameterized querIEs to avoID sql injections.

哦,绝对是的.

My question is,how can I do this when I’m passing the query as a string parameter?

您根本不应该将查询作为字符串参数传递.相反,您应该将查询作为包含占位符的字符串参数和这些占位符的值传递:

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}
总结

以上是内存溢出为你收集整理的c# – 参数化查询与SQL注入全部内容,希望文章能够帮你解决c# – 参数化查询与SQL注入所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1246705.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-07
下一篇2022-06-07

发表评论

登录后才能评论

评论列表(0条)

    保存