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.