I have been writing some simple c# and I usually use the same class and functions that insert and grab the data from the database.
For example, this is my function:
public bool insert_and_ConfirmSQL(String Query, String comments)
{
bool success = false;
NpgsqlCommand cmd = new NpgsqlCommand();
NpgsqlConnection mycon = new NpgsqlConnection();
string connstring = String.Format("Server={0};Port={1}; User Id={2};Password={3};Database={4};timeout=1000;CommandTimeout=120;", tbHost, tbPort, tbUser, tbPass, tbDataBaseName);
mycon.ConnectionString = connstring;
cmd = mycon.CreateCommand();
cmd.CommandText = Query;
mycon.Open();
int temp = 0;
try
{
temp = cmd.ExecuteNonQuery();
success = true;
}
catch
{
if (mycon.State == ConnectionState.Open)
{
mycon.Close();
}
}
return success;
}
Now I know that this query is not safe against injections and I need to use prepared statements. But I don’t understand how should I approach this when each of my queries is different? is there a “universal” function that inserts any query and “prepares” it?
If you are looking for a more generalized way of performing inserts/updates/deletes, perhaps the following is suitable (uses SqlClient but is easily adapted for NpgsqlClient):
Call statement:
Note that you can pass this method an SQL string that includes parameters as well as a stored procedure.