问题: 我试图使用C#中的Oledb接口将日期时间插入到访问数据库中。将日期时间插入到访问
黑客的解决方案:我的生成在插入的字符串,而无需使用command.Properties
我可以插入文本没有问题的数据库,而是试图日期时间的时候,我结束了这个错误:System.Data.OleDb。 OleDbException {“标准表达式中的数据类型不匹配。”}
有几个帖子与此类似,但唉,没有工作解决方案。
这里是我的代码:
void TransferData()
{
string instCmd = Get_InsertCommand(0); // hard coded table 0 for testing
Fill_ProductTable_ToInsert();
con.Open();
// It would be nice not to have to separate the date indexes
int[] textIndex = { 0, 1, 2, 3, 4, 7 };
int[] dateIndex = { 5, 6 };
try
{
foreach (DataRow row in DataToStore.Tables[0].Rows)
{
OleDbCommand command = new OleDbCommand();
command.Connection = con;
command.CommandText = instCmd;
foreach(int j in textIndex)
command.Parameters.AddWithValue("@" + j, row[j]);
foreach (int j in dateIndex)
{
// TESTING CODE
///////////////////////////////////////////////////////////////////////////
string input = "#\'" +DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") +"\'#";
command.Parameters.AddWithValue("@" + j, input.ToString());
Program.WriteLine(input.ToString());
///////////////////////////////////////////////////////////////////////////
}
command.ExecuteNonQuery();
}
}
finally
{
con.Close();
}
}
string Get_InsertCommand(int i)
{
string sqlIns = "INSERT INTO " + DataToStore.Tables[0].TableName + " (";
string temp = "VALUES (";
for (int j = 0; j < expected_header[i].Length - 1; j++)
{
sqlIns += expected_header[i][j] + ", ";
temp += "@" + j + ", ";
}
int lastIndex = expected_header[i].Length -1;
sqlIns += expected_header[i][lastIndex] + ") ";
temp += "@" + lastIndex + ")";
sqlIns += temp;
return sqlIns;
}
内的区域标记测试代码,我已经试过的日期时间,我能想到的每一个排列。 (), 我试过了#和' 我试过这些格式:yyyy-MM-dd,yyyyMMdd,yyyy \ MM \ dd,yyyy/MM/dd 我也试过ToOADate() ToString(),ToShortDateString()
我也尝试设置数据库接受ANSI-92与SQL
我跑出来的想法。
注:此代码设置为处理来自多个数据库的多个表,介意环......
同样的错误,使用OleDbType.Date和OleDbType.DBDate与许多变化的日期时间输入,包括DateTime.Now,DateTime.Now.Date,新的日期时间(2012,2,3),所有到同一端。 – user1642357
在执行之前将您生成的sql语句打印到控制台,并验证它是否正确 –
如何从OleDbCommand对象打印完整命令? 命令格式是正确的,它适用于字符串值,如果我将数据库中的字段切换到字符串,我可以将日期放入字段中,但我想将日期作为实际日期。 – user1642357