【问题标题】:Data Type Mismatch error in Criteria expression in Select query C# query选择查询 C# 查询中条件表达式中的数据类型不匹配错误
【发布时间】:2015-06-29 08:59:04
【问题描述】:

我的示例代码如下,我收到以下错误;

条件表达式中的数据类型不匹配错误。

Details => ScannerAlarmLimits 是我来自 .mdb 数据库的表。

string jointS = dsetChamberS1.Tables[0].Rows[tot][0].ToString();
int select1S = Convert.ToInt32(jointS);
string sqlQuery1S = "SELECT TMin,TMax,HMin,HMax from ScannerAlarmLimits WHERE ScannerID='" +select1S+ "'";
OleDbCommand cmd1S = new OleDbCommand(sqlQuery1S, conn);
OleDbDataAdapter adapter1S = new OleDbDataAdapter(cmd1S);
adapter1S.Fill(dsetTempS, "ScannerAlarmLimits");

【问题讨论】:

  • ScannerID 字段的类型是什么,为什么不使用参数化 SQL?
  • ScannerID 是整数..
  • 很抱歉,我对参数化查询知之甚少。
  • 现在是了解参数化 SQL 的好时机,您的项目成为 SQL 注入攻击的受害者之前...

标签: c# ms-access-2007


【解决方案1】:

我刚刚在 where 子句的条件中添加了单引号,现在它可以工作了。

var query = "SELECT * from  checkinout where read <> '1'";

【讨论】:

    【解决方案2】:

    如果您的ScannerID 列是整数,那么您不应使用单引号。单引号用于字符。喜欢;

    WHERE ScannerID = " + select1S;
    

    但作为一种更好的方法,您应该始终使用parameterized queries。这种字符串连接对SQL Injection 攻击开放。又名bobby-tables

    并使用using statement 来处理您的连接、命令和适配器。

    string jointS = dsetChamberS1.Tables[0].Rows[tot][0].ToString();
    int select1S = Convert.ToInt32(jointS);
    using(var conn = new OleDbConnection(conString))
    using(var cmd1S = conn.CreateCommand())
    {
        cmd1S.CommandText = "SELECT TMin,TMax,HMin,HMax from ScannerAlarmLimits WHERE ScannerID = @id";
        cmd1S.Parameters.AddWithValue("@id", OleDbType.Integer).Value = select1S;
    
        using(var adapter1S = new OleDbDataAdapter(cmd1S))
        {
            adapter1S.Fill(dsetTempS, "ScannerAlarmLimits");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多