0

我正在尝试在 c# 中创建一个可重用的 MySQL 数据库类,但我担心保持它的安全(可能的业务用途)。我做了很多阅读,人们建议使用参数将数据添加到表中并获取它等。我的问题是通过许多不同的表保持类可重用我的插入方法目前(在数据库类中):

public void Insert(string incomingQuery) //Insert Statement
{
    //Assign the incomingQuery for use.
    string query = incomingQuery;

    //Open Database Connection
     if(this.OpenConnection() == true)
     {
         //Create command and assign the query and connection from the constructor
         MySqlCommand command = new MySqlCommand(query, connection);

        //Execute the command
        command.ExecuteNonQuery();

        //Close the connection
        this.CloseConnection();
    }

}

我的Create方法从另一个类(Users)传递 SQL 查询:

public void Create()
{
    //Add a new user to the database
    string sqlQuery = "INSERT INTO Users(first_name, last_name, pc_username) VALUES('" + firstName + "','" + lastName + "','" + userName + "');";
    database.Insert(sqlQuery);
    Login();
}

我怎样才能使它更安全?

4

3 回答 3

2

我怎样才能使它更安全?

使用参数。您当前的查询容易受到SQL 注入的影响。

此外,您的方法似乎有一个打开的连接,最好尽可能晚地打开数据库连接,然后尽早关闭它。对你的连接使用using 语句并在你的方法中打开它,因为 Connection 和 Command 实现IDisposable了接口,它将确保它的处理(关闭连接)。

于 2013-11-01T13:22:11.143 回答
1

使用 MySQL 数据库中的存储过程,然后使用所需参数调用这些过程。编写实用程序方法,以便它们采用键值对字典,并将其解析为 OdbcCommand 的参数属性

在c#中调用带参数的存储过程

foreach(KeyValuePar kvp in dictionary)
{
    command.Parameters.Add(kvp.Key).Value = kvp.Value;
}

我忘记了确切的代码...

于 2013-11-01T13:25:15.020 回答
0

Pass all the parameters (firstName, lastName etc) as a string[] (or better, a Dictionary) to a method resembling the following:

AddParamsToCommand(SqlCommand cmd, Dictionary<string,string> paramList)
{
    foreach (string s in paramList.Keys)
    {
        sqlParameter p = cmd.CreateParameter();
        p.Name = s;
        p.Value = paramList[s];
        cmd.Parameters.Add(p);
    }
}

Just as an example.

Edited since I've been using OleDB and forgot about putting names on params in for SqlCommands.

于 2013-11-01T13:27:08.137 回答