How to use OleDbParameter to update and insert data in Access?
Data can be updated and inserted using parameterized queries with the use of the OleDbParameter object.
Update data example:
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
string query = "UPDATE [TableName] SET [Column1] = ?, [Column2] = ? WHERE [ID] = ?";
using (OleDbCommand command = new OleDbCommand(query, connection))
{
command.Parameters.AddWithValue("@Column1Value", newValue1);
command.Parameters.AddWithValue("@Column2Value", newValue2);
command.Parameters.AddWithValue("@IDValue", id);
command.ExecuteNonQuery();
}
}
Example of inserting data:
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
string query = "INSERT INTO [TableName] ([Column1], [Column2]) VALUES (?, ?)";
using (OleDbCommand command = new OleDbCommand(query, connection))
{
command.Parameters.AddWithValue("@Column1Value", value1);
command.Parameters.AddWithValue("@Column2Value", value2);
command.ExecuteNonQuery();
}
}
In the example, connectionString represents the connection string, TableName is the name of the table, Column1 and Column2 are the column names to be updated or inserted. @Column1Value, @Column2Value, and @IDValue are parameter names, while newValue1, newValue2, id, value1, and value2 represent their respective values. By adding parameters and assigning values to them, parameterized queries can be implemented to prevent SQL injection attacks and improve the performance and security of queries.