访问类型不匹配
本文关键字:不匹配 访问类型 | 更新日期: 2023-09-27 18:23:37
有两个表:
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)
我不明白错误。。。。
知道怎么了吗?
来自MSDN:
OLE DB.NET提供程序不支持用于传递的命名参数SQL语句或由调用的存储过程的参数当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)
并且,您必须按照与查询中出现的参数相同的顺序添加参数。
将其更改为:
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();
}
}
现在它似乎起作用了。。。不过有点奇怪。。。