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

时间:2017-02-20 10:49:18

标签: c# ms-access qsqlquery

\我在访问数据库表(DATA)中有三列,如下所示

enter image description here

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

我使用了DELETE from DATA Where Name='A' and Date='1/1/2017' 这给出了#34;类型不匹配错误"!

以下是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();
}

1 个答案:

答案 0 :(得分:3)

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

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();
}

通过这种方式,您不会留下空间来解释您的值的解释(从字符串到日期的转换),但您要准确告诉您的数据库引擎您的价值是什么。当然,如果您指定了正确的类型,则不会出现类型不匹配错误