我正在使用带有 SqlBulkcopy 的 c# 控制台应用程序将一些 excel 文件导入 sql server,并在导入日期时间值时收到以下异常。
异常:当我们要进行批量复制时,会出现此异常,其中一个或多个列具有日期时间数据类型。我认为它与下面的日期格式有关是错误详细信息。
“来自数据源的字符串类型的给定值无法转换为指定目标列的日期时间类型。”
代码片段
sExcelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelFilePath + ";Extended Properties=" + "\"Excel 12.0;HDR=No;IMEX=1;\"";
OleDbConnection OleDbConn = new OleDbConnection(sExcelConnectionString);
OleDbTransaction tran;
OleDbCommand OleDbCmd = new OleDbCommand(myExcelDataQuery, OleDbConn);
OleDbConn.Open();
OleDbDataReader dr = OleDbCmd.ExecuteReader();
if (dr.HasRows && dr.FieldCount > 1)
{
//DataTable dt = readReader(dr);
try
{
string sSqlConnectionString = connectionString.ToString();
string sClearSQL = "DELETE FROM " + sSQLTable;
SqlConnection SqlConn = new SqlConnection(sSqlConnectionString);
SqlCommand SqlCmd = new SqlCommand(sClearSQL, SqlConn);
SqlConn.Open();
//SqlCmd.ExecuteNonQuery();
SqlConn.Close();
SqlBulkCopy bulkCopy = new SqlBulkCopy(sSqlConnectionString);
bulkCopy.DestinationTableName = sSQLTable;
bulkCopy.BulkCopyTimeout = 0;
while (dr.Read())
{
bulkCopy.WriteToServer(dr);
imported = true;
}
OleDbConn.Close();
if (valToField.ToString() != "")
{
sClearSQL = "DELETE FROM " + sSQLTable + " where " + valToField + "='" + valToRemove.ToString() + "'";
SqlCmd = new SqlCommand(sClearSQL, SqlConn);
SqlConn.Open();
SqlCmd.ExecuteNonQuery();
}
SqlConn.Close();
}
catch (Exception ex)
{
LogMessageToFile("Error While Inserting Data from : " + excelFilePath.ToString() + " to table : " + dbtable.ToString() + ex.Message.ToString());
}
}
请提出解决方案
谢谢