解決不能將DataTable資料批量更新到資料庫的問題
問題描述:從excel檔案使用OLEDB方式讀取資料到DataTable中,然後將DataTable資料更新到access資料庫,這時由於DataTable中的每一行的RowStated狀態都是unChanged而無法通過UpdateCommand方式更新到資料庫。
解決方法:將從excel檔案讀取的資料儲存到dt1(DataTable型別)中,然後將dt1的每行資料分別拷貝給row(DataRow型別),將row依次加入到dt_result(DataTable)型別,然後將dt_result使用UpdateCommand方式批量匯入到access資料庫。
方法一:
DataTable dt = ExcelHelper.FastGetDataFromExcel(“C:\\test.xls”);
BatchUpdateDatabase (dt, “test”)
方法二:
DataTable dt = ExcelHelper.FastGetDataFromExcel(“C:\\test.xls”);
BatchUpdateDatabase (this.CopyDataTable(dt), “test”)
方法一無法更新到資料庫,但是方法二可以。
/// <summary>
/// 通過OLEDB方式從excel讀取資料
/// </summary>
/// <param name="fullFileName">excel檔名</param>
/// <returns>獲取讀取資料的表</returns>
static public DataTable FastGetDataFromExcel(string fullFileName)
{
string strCon =string.Format("Provider=Microsoft.Ace.OLEDB.12.0;Data Source='{0}';Extended Properties="+
"'Excel 8.0;HDR=YES;IMEX=1;'", fullFileName);
OleDbConnection oldCon=null;
try
{
oldCon = new OleDbConnection(strCon);
oldCon.Open();
int index = fullFileName.LastIndexOf("\\");
string fileName=fullFileName.Substring(index+1,fullFileName.Length-index-1);
string sql = "select * from [sheet1$]";
OleDbDataAdapter adp = new OleDbDataAdapter(sql,oldCon);
DataTable dt = new DataTable();
adp.Fill(dt);
return dt;
}
catch (Exception e)
{
throw e;
}
finally
{
oldCon.Close();
}
}
private DataTable CopyDataTable(DataTable dt_source)
{
DataTable dt_result = dt_source.Clone();
dt_result.Rows.Clear();
int N = dt_source.Columns.Count;
foreach (DataRow row in dt_source.Rows)
{
DataRow myrow = dt_result.NewRow();
myrow.ItemArray = row.ItemArray;
dt_result.Rows.Add(myrow);
}
return dt_result;
}
/// <summary>
/// 使用datatable資料批量更新資料庫(ACCESS)
/// </summary>
/// <param name="dt">資料表</param>
/// <param name="tableName">資料庫中對應表的表名</param>
/// <returns></returns>
public bool BatchUpdateDatabase(DataTable dt, string tableName)
{
try
{
this.OpenConnection();
OleDbDataAdapter sda = new OleDbDataAdapter();
string sql = string.Format("select * from {0}", tableName);
sda.SelectCommand = new OleDbCommand(sql, cnn);
OleDbCommandBuilder builder = new OleDbCommandBuilder(sda);
//sda.UpdateCommand = builder.GetUpdateCommand();
sda.InsertCommand = builder.GetInsertCommand();
int n=sda.Update(dt);
dt.AcceptChanges();
return n>0?true:false;
}
catch (Exception e)
{
throw e;
}
finally
{
this.CloseConnection();
}
}