I am working on a program which use OLEDB to connect to a MS Access 2007 file. My program has a possibility to add and delete records from file by using SQL statements which select deleted item by ID.
Now, I was warned that my code might cause SQL injection which would delete all entries from the file. How can I prevent this? Where lies the problem? One person mentioned that I could avoid it by having good field verification, but what should I verify for?
This is how I delete items:
// SQL query which will delete entry by using entry ID.
string SQL = "DELETE FROM PersonalData WHERE DataID = " + txtEntryID.Text;
private void DeleteData(string SQL)
{
// Creating an object allowing me connecting to the database.
// Using parameters in command will avoid attempts of SQL injection.
OleDbConnection objOleDbConnection = new OleDbConnection();
// Creating command object.
objOleDbConnection.ConnectionString =
"Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + filePath + ";" +
"Persist Security Info=False;" +
"Jet OLEDB:Database Password=" + pass + ";";
OleDbCommand objOleDbCommand = new OleDbCommand();
objOleDbCommand.CommandText = SQL;
// Assigning a connection string to the command.
objOleDbCommand.Connection = objOleDbConnection;
try
{
// Open database connection.
objOleDbConnection.Open();
objOleDbCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
// Displaying any errors that
// might have occured.
MessageBox.Show("Error: " + ex.Message);
}
finally
{
// Close the database connection.
objOleDbConnection.Close();
}
// Refreshing state of main window.
mainWindow.DisplayFileContent(filePath);
lblMessage.Text = "Data was successfully deleted.";
// Clearing text box field.
txtEntryID.Clear();
}
if(int.TryParse(str, out i))
– Arjan Einbu Dec 1 '11 at 19:42