熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

簡便的將DataSet導入到數據庫中

2013-11-13 09:45:43  來源: .NET編程 

  有時候我們需要經常的將數據集(DataSet)導入到數據庫中可是怎麼辦呢? 有人就說了利用Sql語句馬上就可以搞定了sql是可以搞定但是sql的拼接不可以有差錯啊利用SqlParameter可以減少類型的煩惱可是如果是很多列那還不累死你
將DataSet導入Access中(OleDbDataAdapterUpdate方法 )

  OleDbConnection olecon = new OleDbConnection(Provider=MicrosoftJetOLEDB;Data Source= + fileName + ;Jet OLEDB:Engine Type=);
oleconOpen();
OleDbDataAdapter oda = new OleDbDataAdapter(select * from TableName olecon);
DataSet newds = new DataSet();
try
{
OleDbCommandBuilder cmdbld = new OleDbCommandBuilder(oda);
cmdbldSetAllValues = true;
odaInsertCommand = cmdbldGetInsertCommand();
dsTables[i]BeginLoadData();
int rowcount = dsTables[i]RowsCount;
for (int n = ; n < rowcount; n++)
{
dsTables[i]Rows[n]SetAdded();
}
dsTables[i]EndLoadData();
odaUpdateBatchSize = ;
}
catch
{
}
odaUpdate(ds dsTables[i]TableName);
odaDispose();

  oleconClose();
oleconDispose();
OleDbDataAdapterUpdate方法和用Sql拼接插入的效率基本上是一樣的OleDbDataAdapterUpdate
其實也是一條一條的插入更新的但是他可以提高我們程序的穩定性
將DataSet導入到Sql Server中(SqlBulkCopy方法)
SqlConnection conn = new SqlConnection(sqlConnectString);
                connOpen();
                SqlBulkCopy sbc = new SqlBulkCopy(conn);
                sbcDestinationTableName = dsTables[i]TableName;
                //將數據集合和目標服務器的字段對應
                for (int q = ; q < dsTables[i]ColumnsCount; q++)
                {
                    sbcColumnMappingsAdd(dsTables[i]Columns[q]ColumnName dsTables[i]Columns[q]ColumnName);
                }
                try
                {
                    sbcWriteToServer(dsTables[i]);
                }
                catch //(Exception ex)
                {
                    //throw ex;
                     continue;
                }
                finally
                {
                    dsDispose();
                    connClose();
                    sbcClose();
                }
這個是不是也比sql insert也好多了這個效率要比SQL Insert快多了


From:http://tw.wingwit.com/Article/program/net/201311/11522.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.