C#访问条件表达式中的OleDb数据类型不匹配
请检查以下代码中是否存在导致“条件表达式中的数据类型不匹配”异常的错误?我就是找不到问题的根源 *C#访问条件表达式中的OleDb数据类型不匹配,c#,ms-access,oledbexception,oledbparameter,C#,Ms Access,Oledbexception,Oledbparameter,请检查以下代码中是否存在导致“条件表达式中的数据类型不匹配”异常的错误?我就是找不到问题的根源 *record.Date可为空的DateTime?类型显式强制转换为DateTime *record.Date被设置为可为空,用于程序中的其他用途。但是为插入操作设置的record.Date是从日期时间选择器检索的,因此此方法的record.Date值决不能为空 在哪里 (如果你想知道) 从我的访问文件(设计视图)中: 谢谢大家! 下面是AddRecord方法。谢谢 public sta
record.Date
可为空的DateTime?
类型显式强制转换为DateTime
*record.Date
被设置为可为空,用于程序中的其他用途。但是为插入操作设置的record.Date
是从日期时间选择器检索的,因此此方法的record.Date
值决不能为空
在哪里
(如果你想知道)
从我的访问文件(设计视图)中:
谢谢大家!
下面是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();
}
}
将DBNull.Value转换为(object)DBNull.Value;是处理对象的正确方法吗?试试这个,我刚才检查了一下,做了一个类似的测试,效果很好……所以…[问题解决]:D 我从中学到了这一点 标准表达式中的不匹配问题是由于 分配给用于表示日期时间的参数的OleDbType。现在 调用AddWithValue时的值 AddWithValue选择的OLEDB类型为DBTimeStamp,但Access需要 一个OleDbType.Date 这意味着方便的
AddWithValue
在我身上拉了一个快速的
感谢@LarsTech和@DJKraze在演示混乱的情况下帮助我 我认为您还可以使用ToString()将日期数据转换为access可以接受的正确格式
insertCommand.Parameters.AddWithValue("@Date", record.Date.ToString("dd-MM-yy"));
在您的案例中,什么是
记录
。。你能展示一下那个结构吗。。此外,您还需要检查record.DateTime是否为空,或者将其强制转换为DBNULL如果为空,您可以显示更多的代码声明。。您是否熟悉“null合并运算符?”`soinsertCommand.Parameters.AddWithValue(“@Date”,record.Date??DBNull.Value))“代码>也许会为混乱而担忧,@DJKRAZE。”。编辑!您正在分配数据时间?作为可空类型,我想知道为什么要分配可空类型?无论是哪种方式,我都发布了一个工作解决方案,将来当您将其声明为可为null的属性时,该解决方案应该适用于您。
?使用`null coalescing operator`record.getDBType()
这是不需要的,因为它根本不会返回值。事实上,我认为它会返回System.String或error。您能告诉我们这些更改是否对您有效吗?是的,“AddWithValue”让我好了几个小时。。。如果我没有看到这篇文章,我就不会看到AddWithValue选择了不同的类型。问题解决了,是的。此外,您还注意到问题的基本原理。但你没有写下你为解决问题所做的实际工作。
insertCommand.Parameters.AddWithValue("@Date", record.Date.ToString("dd-MM-yy"));