C# 访问类型不匹配
有两张桌子:C# 访问类型不匹配,c#,ms-access,parameterized-query,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) {
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)
我不明白这个错误
有什么问题吗?来自:
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();
}
}
现在它似乎起作用了。。。虽然有点奇怪…如果您是对的,但如果按正确的顺序放置命名参数,它仍然可以工作。是否尝试使用?相反,但仍然失败…但如果我改变两个参数的顺序,它似乎可以工作???你是说当你第一次添加@freq参数到集合中时,它就工作了?是的,当我第一次添加@freq时,它就工作了。。。。不知道Access是否先执行“@freq”选择。。。虽然这也有点奇怪。。。