阅读量:0
使用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注入攻击,并提高查询的性能和安全性。