访问类型不匹配

时间:2013-07-18 05:38:04

标签: c# ms-access parameterized-query

有两张桌子:

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

我不断收到“条件表达式中数据类型不匹配”的异常。

如果我更改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)

我没有收到错误....

知道出了什么问题?

2 个答案:

答案 0 :(得分:1)

来自MSDN

  

OLE DB .NET提供程序不支持传递的命名参数   SQL语句或由a调用的存储过程的参数   CommandType设置为Text时的OleDbCommand。在这种情况下,   必须使用问号(?)占位符。例如:

因此请将您的查询更改为:

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

您必须按查询中出现的顺序添加参数。

答案 1 :(得分:0)

将其更改为:

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

现在似乎工作......虽然有点奇怪......