使用 SQL 查询从 Access 中删除数据 - C#

Delete data from Access using SQL Query - C#

\我在 access 数据库中有三列 table (DATA) 如下所示

我只想根据 SQL 查询中 WHERE 子句中的两个条件删除一些行;例如,当 NAME = "A" 和 Date = "1/1/2017"

时删除行

我用过DELETE from DATA Where Name='A' and Date='1/1/2017' 这给 "type mismatch error"!

这是 C# 中的代码:

 using (OleDbConnection thisConnection = new OleDbConnection(connectionname))
 {
    string deletequery = " DELETE FROM DATA WHERE [Name] = 'A' And [Date] = '1/1/2017';

    OleDbCommand myAccessCommandDelete = new OleDbCommand(deletequery, thisConnection);
    thisConnection.Open();
    myAccessCommandDelete.ExecuteNonQuery();
    thisConnection.Close();
}

将值传递给将在查询中使用的数据库引擎的最佳方法是通过参数集合准确指定参数的类型

using (OleDbConnection thisConnection = new OleDbConnection(connectionname))
{
    string deletequery = @"DELETE FROM DATA WHERE [Name] = @name And 
                         [Date] = @date";
    OleDbCommand myAccessCommandDelete = new OleDbCommand(deletequery, thisConnection);
    thisConnection.Open();
    myAccessCommandDelete.Parameters.Add("@name", OleDbType.VarWChar).Value = "A";
    myAccessCommandDelete.Parameters.Add("@date", OleDbType.Date).Value = new DateTime(2017,1,1);
    myAccessCommandDelete.ExecuteNonQuery();
    // not needed -> thisConnection.Close();
}

通过这种方式,您不会让 space 去解释(从字符串到日期的转换)您的值,而是准确地告诉您的数据库引擎您的值是什么。当然,如果您指定了正确的类型,就不会出现类型不匹配错误