Using an OR Statement in a MySQL Parameter

I am trying to build a MySQL query in my C # application, I am wondering if the OR statement can be used in MySQL parameters.

I have a list of names, and I want to check and see what names already exist in the database. Here is a short example

List<string> names = new List<string> {"adam", "bob", "cathy"}; //actual list is much longer
MySqlConnection connection = getAndOpenConnection();
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM Employees WHERE name = @names";
command.Parameters.Add(new MySqlParameters("@names", String.Format("names = {0}", String.Join(names, " or name = ")))); //is this line legal?

My initial idea is to build the command text as follows:

command.CommandText = String.Format("SELECT * FROM Employees WHERE name = '{0}'", String.Join(names, "' or name = '"))

The code will give me the correct command text that I want, but I really want to prevent SQL injection.

Can someone please help me on how to build MySqlCommand correctly?

+4
source share
1 answer

, . IN, , ( ). , :

  • , .

; "dapper", :

connection.Query("SELECT * FROM Employees WHERE name in @names", new { names })
          .ToList();

( List<dynamic>, Employee, , connection.Query<Employee>(...).ToList() List<Employee>).

, , ( ):

var sb = new StringBuilder("SELECT * FROM Employees WHERE name=@name0");
cmd.Parameters.AddWithValue("name0", names[0]);
for(int i = 1; i < names.Count ; i++) {
    sb.Append(" or name=@name").Append(i);
    cmd.Parameters.AddWithValue("name" + i, names[i]);
}
cmd.CommandText = sb.ToString();

:

switch(names.Count)
{
    case 0: cmd.CommandText = "SELECT * FROM Employees"; break;
    case 1:
        cmd.CommandText = "SELECT * FROM Employees WHERE name=@name";
        cmd.Parameters.AddWithValue("name", names[0]);
        break;
    default:
        var sb = new StringBuilder(
            "SELECT * FROM Employees WHERE name IN (@name0")
        cmd.Parameters.AddWithValue("name0", names[0]);
        for(int i = 1;i<names.Count;i++) {
            sb.Append(",@name").Append(i);
            cmd.Parameters.AddWithValue("name" + i, names[i]);
        }
        cmd.CommandText = sb.Append(")").ToString();
        break;
}
+3

Source: https://habr.com/ru/post/1546330/


All Articles