C#访问OleDb标准表达式中的数据类型不匹配
请您检查以下代码是否存在错误,这些错误会导致“标准表达式中的数据类型不匹配”exception? 我似乎无法找到问题的根源……
* record.Date
为空的DateTime?
type显式转换为DateTime
* record.Date
设置为可为空,用于程序中的其他用途。 但是从DateTimePicker检索为INSERT操作设置的record.Date
,因此此方法的record.Date
值永远不应为null 。
哪里
和(如果你想知道)
从我的Access文件(设计视图):
谢谢!
这是AddRecord方法。 谢谢!
public static int AddRecord(Record record) { OleDbConnection connection = LABMeetingRecordsDB.GetConnection(); string insertStatement = "INSERT INTO DocumentInfo " + "([FileName], [Date], [Subject], [Type]) " + "VALUES (?, ?, ?, ?)"; try { OleDbCommand insertCommand = new OleDbCommand(insertStatement, connection); insertCommand.Parameters.AddWithValue("@FileName", record.FileName); insertCommand.Parameters.AddWithValue("@Date", (DateTime)record.Date); insertCommand.Parameters.AddWithValue("@Subject", record.Subject); insertCommand.Parameters.AddWithValue("@Type", record.getDBType()); connection.Open(); insertCommand.ExecuteNonQuery(); string selectStatement = "SELECT IDENT_CURRENT('DocumentInfo') FROM DocumentInfo"; OleDbCommand selectCommand = new OleDbCommand(selectStatement, connection); int recordID = Convert.ToInt32(selectCommand.ExecuteScalar()); AddCategory(connection, recordID, record.Category); return recordID; } catch (OleDbException ex) { throw ex; } finally { connection.Close(); } }
所以…… [问题已解决]:D
从这里我学到了
标准表达式不匹配的问题是由于OleDbType分配给用于表示调用AddWithValue时DateTime.Now值的参数。
AddWithValue选择的OleDbType是DBTimeStamp,但Access需要OleDbType.Date。
这意味着方便的AddWithValue
在我AddWithValue
拉了一个快…
感谢@LarsTech和@DJKraze帮助我,尽管演示文稿混乱!
OleDbConnection connection = LABMeetingRecordsDB.GetConnection(); string insertStatement = "INSERT INTO DocumentInfo " + "([FileName], [Date], [Subject], [Type]) " + "VALUES (?, ?, ?, ?)"; OleDbCommand insertCommand = new OleDbCommand(insertStatement, connection); insertCommand.CommandType = CommandType.Text; insertCommand.Parameters.AddWithValue("@FileName", record.FileName); insertCommand.Parameters.AddWithValue("@Date", (DateTime)record.Date ?? (object)DBNull.Value); insertCommand.Parameters.AddWithValue("@Subject", record.Subject); insertCommand.Parameters.AddWithValue("@Type", record.getDBType ?? (object)DBNull.Value); connection.Open(); try { insertCommand.ExecuteNonQuery(); } catch(OleDbException e) { LogYourMessage(e.Message); }
将DBNull.Value转换为(对象)DBNull.Value; 是处理对象的正确方法尝试这个我刚刚检查我的结束并做了类似的测试工作..
我认为您也可以使用ToString()将您的日期数据设置为正确的格式,访问将接受该格式
insertCommand.Parameters.AddWithValue("@Date", record.Date.ToString("dd-MM-yy"));