简体   繁体   English

访问类型不匹配

[英]Access Type Mismatch

Having two tables: 有两个表:

MyTable1:
  id       AutoNumber
  typecode Text

MyTable2
  id      AutoNumber
  pid     Number
  freq    Number

using System.Data.OleDb;
namespace AccessSelect
{
    class Program
    {
        static void Main(string[] args)
        {
            var sql = @"select 'x' from mytable1 where typecode=@typeCode and EXISTS (
                        select 'x' from mytable2 where (freq=0 OR freq=@freq) and mytable1.id=mytable2.pid)";

            using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=gpi.mdb;Jet OLEDB:Database Password=???"))
            {
                conn.Open();
                OleDbCommand cmd = new OleDbCommand(sql, conn);

                cmd.Parameters.Add(new OleDbParameter("@typeCode", "KK3000"));
                cmd.Parameters.Add(new OleDbParameter("@freq", 50));

                var o = cmd.ExecuteScalar();
            }
        }
    }
}

I keep getting the exception 'Data type mismatch in criteria expression.' 我不断收到异常“条件表达式中的数据类型不匹配”。

If I change the SQL to contain the values: 如果我更改SQL以包含值:

select 'x' from mytable1 where typecode='KK3000' and EXISTS (
 select 'x' from mytable2 where (freq=0 OR freq=50) and  mytable1.id=mytable2.pid)

I don't get the error.... 我没有得到错误...。

Any idea to what is wrong? 有什么问题的主意吗?

From MSDN : MSDN

The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. 当CommandType设置为Text时,OLE DB .NET Provider不支持将命名参数传递给SQL语句或OleDbCommand调用的存储过程的命名参数。 In this case, the question mark (?) placeholder must be used. 在这种情况下,必须使用问号(?)占位符。 For example: 例如:

So change your query to: 因此,将查询更改为:

select 'x' from mytable1 where typecode = ? 
     and EXISTS (select 'x' from mytable2 where (freq=0 OR freq = ?) and mytable1.id=mytable2.pid)

And you have to add parameters in the same order as they occur in query. 并且您必须按与查询中出现的顺序相同的顺序添加参数。

Changed it to: 更改为:

static void Main(string[] args)
{
    var sql = @"select 'x' from mytable1 where typecode=@typeCode and EXISTS (
                select 'x' from mytable2 where (freq=0 OR freq=@freq) and mytable1.id=mytable2.pid)";

    using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=gpi.mdb;Jet OLEDB:Database Password=???"))
    {
        conn.Open();
        OleDbCommand cmd = new OleDbCommand(sql, conn);

        cmd.Parameters.Add(new OleDbParameter("@freq", 50));
        cmd.Parameters.Add(new OleDbParameter("@typeCode", "KK3000"));

        var o = cmd.ExecuteScalar();
    }
}

and now it seems to work... a bit strange though... 现在它似乎可以工作了...虽然有点奇怪...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM