C#循环和质量插入

时间:2013-07-01 18:36:02

标签: c# asp.net loops

以下代码将在我的数据库中插入一些值。它获得6个随机值,将数据放入数组中,然后将其插入数据库中。

    public void LottoTest(object sender, EventArgs e)
    {
        Dictionary<int, int> numbers = new Dictionary<int, int>();
        Random generator = new Random();
        while (numbers.Count < 6)
        {
            numbers[generator.Next(1, 49)] = 1;
        }

        string[] lotto = numbers.Keys.OrderBy(n => n).Select(s => s.ToString()).ToArray();

        foreach (String _str in lotto)
        {
            Response.Write(_str);
            Response.Write(",");
        }


        var connectionstring = "Server=C;Database=lotto;User Id=lottoadmin;Password=password;";

        using (var con = new SqlConnection(connectionstring))  // Create connection with automatic disposal
        {
            con.Open();
            using (var tran = con.BeginTransaction())  // Open a transaction
            {
                // Create command with parameters  (DO NOT PUT VALUES IN LINE!!!!!)
                string sql =
                    "insert into CustomerSelections(val1,val2,val3,val4,val5,val6) values (@val1,@val2,@val3,@val4,@val5,@val6)";
                var cmd = new SqlCommand(sql, con);
                cmd.Parameters.AddWithValue("val1", lotto[0]);
                cmd.Parameters.AddWithValue("val2", lotto[1]);
                cmd.Parameters.AddWithValue("val3", lotto[2]);
                cmd.Parameters.AddWithValue("val4", lotto[3]);
                cmd.Parameters.AddWithValue("val5", lotto[4]);
                cmd.Parameters.AddWithValue("val6", lotto[5]);


                cmd.Transaction = tran;
                cmd.ExecuteNonQuery(); // Insert Record

                tran.Commit();  // commit transaction
                Response.Write("<br />");
                Response.Write("<br />");
                Response.Write("Ticket has been registered!");
            }
        }


    }

将MASS条目循环并插入数据库的最佳方法是什么。可以说,C#的100,000条记录?我希望能够通过我的方法生成随机数并利用我也有的插入..

3 个答案:

答案 0 :(得分:8)

对于真正的大型插页,SqlBulkCopy是您的朋友。执行此操作的简单但低效的方法只是使用数据填充DataTable,然后将其放在SqlBulkCopy,但它可以快两倍(相信我,我已经定时)通过欺骗IDataReader。为方便起见,我最近将此代码移至FastMember,因此您可以执行以下操作:

class YourDataType {
    public int val1 {get;set;}
    public string val2 {get;set;}
    ... etc
    public DateTime val6 {get;set;}
}

然后创建一个迭代器块(即一个非缓冲转发器只读取器):

public IEnumerable<YourDataType> InventSomeData(int count) {
    for(int i = 0 ; i < count ; i++) {
        var obj = new YourDataType {
           ... initialize your random per row values here...
        }
        yield return obj;
    }
}

然后:

var data = InventSomeData(1000000);
using(var bcp = new SqlBulkCopy(connection))
using(var reader = ObjectReader.Create(data))
{ // note that you can be more selective with the column map
    bcp.DestinationTableName = "CustomerSelections";
    bcp.WriteToServer(reader);
}

答案 1 :(得分:1)

您需要Sql批量插入。 msdn http://blogs.msdn.com/b/nikhilsi/archive/2008/06/11/bulk-insert-into-sql-from-c-app.aspx

上有一个很好的教程

答案 2 :(得分:1)

MSDN Table Value Parameters

基本上,您使用要放入SqlServer的数据填充数据表。

DataTable tvp = new DataTable("LottoNumbers");
forach(var numberSet in numbers)
    // add the data to the dataset

然后使用类似于此的代码通过ADO传递数据......

command.Parameters.Add("@CustomerLottoNumbers", SqlDbType.Structured);
command.Parameters["CustomerLottoNumbers"].Value = tvp;

然后你可以使用与此类似的SQL ...

INSERT CustomerSelections
SELECT * from @CustomerLottoNumbers