我已经将数据从excel导入数据库,但是问题是当我具有excel表格值错误时,它将无法插入数据库,并且在插入数据库之前,我已经删除了数据库中的先前条目。 对于插入,我使用了sqlbulkcopy,但是在删除数据库中的先前值之前,我需要检查数据类型。我该怎么做?
例如 上面是我在第一行的excel工作表是正确的,在第二行的Dstatus列中是位,但是在excel中是varchar,所以我需要在删除表中的现有记录之前进行检查
(varchar(4)) (varchar) (bit) (varchar(20))
DID DName DStatus DeviceIPAdd
--------------------------------------------------------------------
D101 test1 True 1.1.1.1
D102 test2 hgpl tplsd
isSuccessDelete = _dbObj.DeleteDeviceRecordsForExcel();//for delete previous record of table
if (isSuccessDelete)
isSuccessInsert = _dbObj.InsertDeviceRecords(dtImportDevice as DataTable);
和用于sqlbulkcopy
public bool InsertDeviceRecords(DataTable table)
{
bool isResultAdd = false;
bool expError = false;
string expMessage = string.Empty;
using (SqlBulkCopy bulkcopy = new SqlBulkCopy(_dbConn))
{
bulkcopy.DestinationTableName = @"DEVICEINFO";
try
{
_dbConn.Open();
AutoMapColumns(bulkcopy, table);
bulkcopy.WriteToServer(table);
isResultAdd = true;
_dbConn.Close();
}
catch (Exception e)
{
expMessage = e.Message;
expError = true;
}
finally
{
if (_dbConn.State == ConnectionState.Open)
_dbConn.Close();
if (expMessage.Length > 0 && expError)
{
DialogBox.Show(null, @"Unexpected error occured while inserting DeviceInfo in database", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
return isResultAdd;
}
public static void AutoMapColumns(SqlBulkCopy sbc, DataTable dt)
{
foreach (DataColumn column in dt.Columns)
{
sbc.ColumnMappings.Add(
new SqlBulkCopyColumnMapping(column.ColumnName, column.ColumnName));
}
}