gpt4 book ai didi

C# 和 MySQL .NET 连接器 - 有什么方法可以防止泛型类中的 SQL 注入(inject)攻击?

转载 作者:IT王子 更新时间:2023-10-28 23:53:56 25 4
gpt4 key购买 nike

我的想法是通过 C# (3.5) Winforms 应用程序通过 MySQL .NET 连接器 6.2.2 与 MySQL 数据库对话,为插入/更新/选择创建一些通用类。

例如:

public void Insert(string strSQL)
{
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(strSQL, connection);
cmd.ExecuteNonQuery();
this.CloseConnection();
}
}

然后我可以在程序的任何地方通过传递一个 SQL 查询字符串来运行有/没有用户输入的查询。

阅读有关 SO 的文章开始让我知道这可能会导致 SQL 注入(inject)攻击(对于任何用户输入值)。是否有清除输入的 strSQL 的方法,或者我是否需要在需要执行数据库功能的每个方法中创建单独的参数化查询?

更新 1:

我的最终解决方案如下所示:

public void Insert(string strSQL,string[,] parameterValue)
{
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(strSQL, connection);

for(int i =0;i< (parameterValue.Length / 2);i++)
{
cmd.Parameters.AddWithValue(parameterValue[i,0],parameterValue[i,1]);
}

cmd.ExecuteNonQuery();
this.CloseConnection();
}}

最佳答案

参数化很容易做到。比清理 SQL 查询容易得多,而且比手动转义更不困惑或更容易出错。

this tutorial page 稍微编辑复制/粘贴因为我觉得懒惰:

// User input here
Console.WriteLine("Enter a continent e.g. 'North America', 'Europe': ");
string userInput = Console.ReadLine();

string sql = "SELECT Name, HeadOfState FROM Country WHERE Continent=@Continent";
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@Continent", userInput);

using (MySqlDataReader dr = cmd.ExecuteReader())
{
// etc.
}

这并没有那么难,是吗? :)

关于C# 和 MySQL .NET 连接器 - 有什么方法可以防止泛型类中的 SQL 注入(inject)攻击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2775692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com