使用OleDbParameter對象可以通過參數化查詢來更新和插入數據。
更新數據示例:
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();
}
}
插入數據示例:
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();
}
}
在示例中,connectionString
是連接字符串,TableName
是表名,Column1
和Column2
是要更新或插入的列名,@Column1Value
、@Column2Value
和@IDValue
是參數名稱,newValue1
、newValue2
、id
、value1
和value2
是參數的值。通過添加參數并為其指定值,可以實現參數化查詢,從而防止SQL注入攻擊,并提高查詢的性能和安全性。