【问题标题】:An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in Select query C#选择查询 C# 中出现“System.Data.OleDb.OleDbException”类型的未处理异常
【发布时间】:2018-09-19 14:43:05
【问题描述】:

我在 MS Access 数据库 (.mdb) 中有一个表,其中包含一堆列。我运行了以下 SQL 查询,它将表中的所有内容返回到我的 C# 应用程序 (Visual Studio 2012 Express)。

Select OperatorNo, DateTime, FuelIssued, PreviousCredit, Term 
From TransAll 
Where Term = 'Invalid'

现在我正在尝试向where 子句添加更多条件。我正在尝试将表名 DateTime 上的日期范围设置在特定范围之间。

这是我通过代码创建的 SQL 选择语句:

Select OperatorNo, DateTime, FuelIssued, PreviousCredit, Term 
From TransAll  
Where Term = 'Invalid' 
  And DateTime Between '2018/6/24 00:00:00' and '2018/6/30 23:59:59'

我将 access 数据库导入 SQL Server express,这样我就可以手动找出 SQL 选择命令,然后修复代码。该代码在 SQL Server 数据库中运行。但是在 C# 代码中,我现在遇到了一个错误:

system.data.dll 中发生未处理的 system.data.oledb.oledbexception 类型的异常。附加信息:条件表达式中的数据类型不匹配。

这是我的代码:

string tmpString = strSelectQuery + strWhereClause;
private DataSet myDS = new DataSet();
oledbDataAdapter MyAdapter = new oledbDataAdapter(tmpString, MyConnection);
MyAdapter.Fill(myDS); //this is where the error happens when I run my code
dgvResults.AutoGenerateColumns = true;
dgvResults.AutoSize = true;
dgvResults.DataSource = myDS;
dgvResults.DataMember = "Table";
dgvResults.ReadOnly = true;

if (dgvResults.RowCount == 0)
     MessageBox.Show("No Data for that Date Range/Week");

任何帮助将不胜感激。

【问题讨论】:

  • 在伪 DateTime 数据周围打勾表示不是 DateTime 的文本。始终使用 SQL 参数。总是

标签: c# ms-access oledb


【解决方案1】:

要使您的 SQL 正常工作,请对日期值的字符串表达式使用 Access SQL 语法:

Select 
    OperatorNo, DateTime, FuelIssued, PreviousCredit, Term 
From 
    TransAll  
Where 
    Term = 'Invalid' 
    And 
    DateTime Between #2018/6/24 00:00:00# And #2018/6/30 23:59:59#

但是,如前所述,使用参数。更容易调试。

【讨论】:

    【解决方案2】:

    正如@Plutonix 已经说过的,使用参数而不是字符串 concat 来创建您的语句将有很大帮助。也可以避免sql注入攻击。

    string query = "Select OperatorNo, DateTime, FuelIssued, PreviousCredit, Term from TransAll where Term = @Term And DateTime Between @Startdate and @Enddate";
    
    var cmd = new OleDbCommand();
    cmd.CommandText = query;
    cmd.Connection = sqlConnection;
    
    cmd.Parameters.Add("@Term", OleDbType.VarChar).Value = termString;
    cmd.Parameters.Add("@Startdate", OleDbType.DBTimeStamp).Value = startDate; // of type date
    cmd.Parameters.Add("@Enddate", OleDbType.DBTimeStamp).Value = endDate; // of type date
    

    这样您就可以知道哪里还会发生错误。请尝试处理sqlconnection等。

    【讨论】:

    • 感谢您的建议。我实际上已经完成了这个项目,而且效果很好。我也在我的新项目中使用了它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-22
    相关资源
    最近更新 更多