Skip to content
Advertisement

How to add parameters to a query when query is unknown length

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.

Advertisement

Answer

Use SqlCommand.Parameters.Add.
Instead of using foreach use for, and add parameter names with appended number "@tok" + i

https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlparametercollection.addwithvalue?view=netframework-4.8

Just example draft code, I didn’t try it:

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement