温馨提示×

Access怎么用OleDbParameter更新和插入数据

小亿
117
2024-01-19 19:20:19
栏目: 编程语言

使用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是表名,Column1Column2是要更新或插入的列名,@Column1Value@Column2Value@IDValue是参数名称,newValue1newValue2idvalue1value2是参数的值。通过添加参数并为其指定值,可以实现参数化查询,从而防止SQL注入攻击,并提高查询的性能和安全性。

0