ado.net datetable批量新增

public QueryResult SqlBulkCopy(DataTable dt, string tableName)
{
    try
    {
        connection.Open();
        using (var copy = new SqlBulkCopy(connection))
        {
            copy.DestinationTableName = tableName;
            copy.WriteToServer(dt);
        }

        return new QueryResult() { result = true };
    }
    catch (Exception ex)
    {
        return new QueryResult() { result = false, msg = ex.Message };
    }
    finally { connection.Close(); }

}

使用

private static void InsertTestData()
{
    var table = new DataTable();

    var sqlOperation = new SqlOperation();

    for (int i = 1; i <= 12; i++)
    {
        table.Columns.Add(new DataColumn("column1" + i, typeof(string)));
    }
    table.Columns.Add(new DataColumn("CreateAt", typeof(DateTime)));


    for (int j = 0; j < 10; j++)
    {
        for (int i = 1; i <= 10000; i++)
        {
            table.Rows.Add(new object[] {
            Guid.NewGuid().ToString().Replace("-","-"),
            Guid.NewGuid().ToString().Replace("-","-"),
            Guid.NewGuid().ToString().Replace("-","-"),
            Guid.NewGuid().ToString().Replace("-","-"),
            Guid.NewGuid().ToString().Replace("-","-"),
            Guid.NewGuid().ToString().Replace("-","-"),
            Guid.NewGuid().ToString().Replace("-","-"),
            Guid.NewGuid().ToString().Replace("-","-"),
            Guid.NewGuid().ToString().Replace("-","-"),
            Guid.NewGuid().ToString().Replace("-","-"),
            Guid.NewGuid().ToString().Replace("-","-"),
            Guid.NewGuid().ToString().Replace("-","-"),
            DateTime.Now
        });
        }
        var result = sqlOperation.SqlBulkCopy(table, "TestTable");
        table.Rows.Clear();
    }
}
posted @ 2024-06-04 16:37  暖暖De幸福  阅读(2)  评论(0编辑  收藏  举报