Im trying to make a generic code for building Insert/Update query. So far i have only created the Update query, but i'mhaving doubts considering SQL injection.
My primary target is trying to create code to decrease the time of retyping the same code over and over.
public SqlConnection SqlConn;
private SqlCommand SqlComm;
public void UpdateRow(string TableName, string UpdateCondition, List<KeyValuePair<string, string>> FieldAndValueList)
{
SqlOpen();
try
{
string UpdateString = $"UPDATE {TableName} ";
int counter = 0;
foreach (KeyValuePair<string, string> FieldAndValue in FieldAndValueList)
{
if (counter > 0) { UpdateString += "," };
UpdateString += $"SET {FieldAndValue.Key} = {FieldAndValue.Value} ";
Counter += 1;
}
if (UpdateCondition.Trim() != "") { UpdateString += $"WHERE {UpdateCondition};"; }
SqlComm = SqlConn.CreateCommand();
SqlComm.CommandText = UpdateString;
SqlComm.ExecuteNonQuery;
}
catch { ShowError(); }
finally { SqlClose(); }
}
It would then be executed like so:
List<KeyValuePair<string, string>> UpdateValues = new List<KeyValuePair<string, string>>;
UpdateValues.Add(new KeyValuePair<string, string>("age", txtAge.text));
UpdateRow("user", "user_id = X", UpdateValues);
Im trying to create it so SQL injection is not possible.
List<KeyValuePair<string, string>> == {"myField", "123; delete from table myTable; --"}The text created will beupdate SomeTable set myField = 123; delete from table myTable; -- UpdateCondition, you'll updateSomeTableand clearMyTableList<KeyValuePair<string, string>>only?FieldAndValueListas a<string,string>is also probably a very bad idea, unless all the values are strings. That isn't the way to do data, basically. If the value is afloat, send it as afloat- otherwise, you can get into a lot of problems with conversions, including things like date formats, and different (international) representations of numbers (commas vs periods, etc)