这些参数有什么问题?

我有一个包含7个字段的Access文件:

DocID - text - primary SourceID - text ReceivedDay - Date/Time Summary - text DueDay - Date/Time Person - text Status - Yes/No 

现在我想用以下代码更新此文件:

 const string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\DocMan.mdb;Persist Security Info=True"; const string InsertQuery = "INSERT Into Docs(DocID,ReceivedDay,Summary,Person,DueDay,Status,SourceID) Values(@DocID,@ReceivedDay,@Summary,@Person,@DueDay,@Status,@SourceID)"; string DocID = textBox1.Text; string SourceID = comboBox1.SelectedIndex.ToString(); DateTime ReceivedDay = dateTimePicker1.Value; string Summary = richTextBox1.Text; string Person = textBox2.Text; DateTime DueDay = dateTimePicker2.Value; bool Status = false; OleDbConnection cnn = new OleDbConnection(ConnectionString); cnn.Open(); OleDbCommand cmd = new OleDbCommand(InsertQuery, cnn); cmd.Parameters.AddWithValue("@DocID", DocID); cmd.Parameters.AddWithValue("@SourceID", SourceID); cmd.Parameters.AddWithValue("@ReceivedDay", ReceivedDay); cmd.Parameters.AddWithValue("@Summary", Summary); cmd.Parameters.AddWithValue("@Person", Person); cmd.Parameters.AddWithValue("@DueDay", DueDay); cmd.Parameters.AddWithValue("@Status", Status); cmd.ExecuteNonQuery(); cnn.Close(); 

但我得到一个例外:

 Data type mismatch in criteria expression. 

我怎样才能解决这个问题?

编辑:我使用不同的方法修复了这个问题:

我构建了一个类似的查询:

 INSERT INTO Docs (DocID, SourceID, ReceivedDay, Summary, Person, DueDay, Status) VALUES (?, ?, ?, ?, ?, ?, ?) 

然后使用TableAdapter来调用它:

 string DocID = textBox1.Text; string SourceID = comboBox1.SelectedIndex.ToString(); DateTime ReceivedDay = dateTimePicker1.Value.Date; string Summary = richTextBox1.Text; string Person = textBox2.Text; DateTime DueDay = dateTimePicker2.Value.Date; bool Status = false; DocManDataSetTableAdapters.DocsTableAdapter docsTableAdapter = new DocManDataSetTableAdapters.DocsTableAdapter(); docsTableAdapter.InsertQuery(DocID,SourceID,ReceivedDay,Summary,Person,DueDay,false); 

更简单,它现在工作正常。 谢谢你们

简单地问谷歌 ,我猜超过10000次点击令人印象深刻。 在你certificate之前你的论点“我不认为……”是无效的。

这就是MSDN所说的:

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

 SELECT * FROM Customers WHERE CustomerID = ? 

因此, OleDbParameter对象添加到OleDbParameterCollection必须直接对应于命令文本中参数的问号占位符的位置。

问题是因为添加参数时参数的顺序不同

例如,在您的注释行( //adapter.InsertQuery... )中,您有DocID ,然后是RecievedDay …但是当您添加它们时,首先添加DocID ,然后添加SourceID

确保它们的顺序相同……这适用于sql语句或存储过程。

这是因为ADO.NET在使用OLEDB提供程序时不支持命名参数,并且由于您连接到Access DB,因此您实际上使用的是OLEDB提供程序…因此参数的顺序很重要。


如果它们是有序的,并且它仍然不起作用,那么我认为它可能是DateTime的一个问题;
尝试将其转换为字符串,然后将其添加为参数:

 cmd.Parameters.AddWithValue("@ReceivedDay", ReceivedDay.ToShortDateString()); cmd.Parameters.AddWithValue("@DueDay", DueDay.ToShortDateString()); 

并确保日期格式为美国格式( m/d/yyyy )或ISO格式( yyyy-mm-dd

OleDb不支持命名参数,所以Dreas的答案是正确的。

当您使用OleDb时,您必须以与查询中显示的顺序相同的顺序添加参数,因为不会使用您提供的名称。