I am working on a project where multiple rows are needed to be added to a MySQL table, due to the high latency of the connection I am trying to add all the values in one command to save time.
So far I have a SQL query that is determined by a string array(each string being a “token”), this, being done with a foreach loop which is adding a value on the to insert query, however, this method is making it difficult to prevent SQL injection as I cannot find a way to add parameters the command. I am unfamiliar with other methods of preventing injection but open to new ideas.
x
query = "INSERT INTO tokenlist(token, user_id) VALUES";
foreach (string tok in tokens)
{
query += " ('" + tok + "', " + logedinId + "),";
}
if (query != "INSERT INTO tokenlist(token, user_id) VALUES")
{
query = query.Remove(query.Length - 1);
query += ";";
if (OpenConnection() == true) {
MySqlCommand cmd = new MySqlCommand(query, mysqlcon);
cmd.ExecuteNonQuery();
CloseConnection();
}
}
Advertisement
Answer
Use SqlCommand.Parameters.Add
.
Instead of using foreach
use for
, and add parameter names with appended number "@tok" + i
Just example draft code, I didn’t try it:
var tokens = new List<dynamic>() { new { tok = 1, logedinId = 2 }, new { tok = 1, logedinId = 2 } };
var query = "INSERT INTO tokenlist(token, user_id) VALUES";
SqlCommand cmd = new SqlCommand(query, new SqlConnection());
for (int i = 0; i < tokens.Count; i++)
{
var tokName = $"@tok{i}";
var logedinIdName = $"@logedinId{i}";
var token = tokens[i];
query += $" ({tokName}, {logedinIdName}),";
cmd.Parameters.Add(new SqlParameter(tokName, SqlDbType.Int)).Value = token.tok;
cmd.Parameters.Add(new SqlParameter(logedinIdName, SqlDbType.Int)).Value = token.logedinId;
}
if (tokens.Any())
{
query = query.Remove(query.Length - 1);
query += ";";
cmd.ExecuteNonQuery();
}