2

Here's the schema for TABLE1:

CREATE TABLE [dbo].[TABLE1] 
(
    [id] [int] IDENTITY(1, 1) NOT NULL,
    [code] [int] NOT NULL,
    [description] [varchar](256) NOT NULL,
    [value] [numeric](18,2) NOT NULL
)

Here's my SqlBulkCopy code:

DataTable data = new DataTable();
data.Columns.Add("code", typeof(int));
data.Columns.Add("description", typeof(string));
data.Columns.Add("value", typeof(decimal));
foreach (Item item in items)
{
    data.Rows.Add(item.Code, item.Description, item.Value);
}

SqlConnection sqlConn = new SqlConnection(_connstr);
sqlConn.Open();
SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConn, SqlBulkCopyOptions.TableLock, sqlConn.BeginTransaction());
bulkCopy.DestinationTableName = "TABLE1";
bulkCopy.ColumnMappings.Clear();
foreach (DataColumn col in dt.Columns)
{
    bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(col.ColumnName, col.ColumnName));
}

bulkCopy.WriteToServer(dt);
sqlConn.Close();

When debugging through it, everything looks good but after the WriteToServer function has been called, no data is added to the database. I've tried not resetting the column mappings but that gives error due to IDENTITY column. Not sure what else could be wrong.

4

1 回答 1

7

看起来您从未提交过交易。您需要存储对您启动的事务的引用,并提交它:

var transaction = sqlConn.BeginTransaction();
SqlBulkCopy bulkCopy = new SqlBulkCopy(
    sqlConn,
    SqlBulkCopyOptions.TableLock, 
    transaction
);

接着

transaction.Commit();

在调用执行批量复制之后和关闭连接之前。

于 2013-07-17T21:25:01.913 回答