c# - 选择查询 C# 中出现“System.Data.OleDb.OleDbException”类型的未处理异常
问题描述
我在 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");
任何帮助将不胜感激。
解决方案
正如@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 等。
推荐阅读
- amazon-web-services - Amazon Athena 跨账户访问
- javascript - 克隆javascript对象省略一个属性
- php - 检查日期是周六还是周日
- jupyter-notebook - Jupyter-lab:转到以前活动的单元格
- docker - windows 10下docker的代理只对http有效,对https无效
- software-collections - 构建 perl526 程序的软件集合
- haskell - 输出 1 到 8 的所有实例,其中一个数字的拼写长度大于一个值的拼写长度?
- php - .on('click') 与通配符未按预期委托
- c# - MVC Core:当前上下文中不存在名称“会话”
- c# - 如何比较按钮参考的背景图像?