使用QueryCommand对象批量插入

时间:2015-08-05 06:27:41

标签: c# sql-server c#-4.0 bulkinsert

是否有关于如何使用QueryCommand批量插入数据库的教程。这是我现在使用的代码:

QueryCommand cmd = conn.CreateCommand();            
try
{
    foreach (MyObj obj in list)
    {
        cmd.Parameters.Clear();
        cmd.CommandText = "INSERT INTO " + MY_TABLE + " (name, type) VALUES (?,?)";
        cmd.Parameters.Add("@name", OdbcType.VarChar).Value = obj.name != null ? obj.name : DBNull.Value.ToString();
        cmd.Parameters.Add("@type", OdbcType.VarChar).Value = obj.type != null ? obj.type.ToString() : DBNull.Value.ToString();

        cmd.ExecuteNonQuery();
    }
}

这是正确的做法吗?
它会为每次迭代触发单独的查询吗?

1 个答案:

答案 0 :(得分:3)

您可以使用SqlBulkCopy

这里是SqlBulkCopy代码的一个简单示例:

using System.Data.SqlClient;

DataTable table = new DataTable("States");
// construct DataTable
table.Columns.Add(new DataColumn("id_state", typeof(int))); 
table.Columns.Add(new DataColumn("state_name", typeof(string)));

// note: if "id_state" is defined as an identity column in your DB,
// row values for that column will be ignored during the bulk copy
table.Rows.Add("1", "Atlanta");
table.Rows.Add("2", "Chicago");
table.Rows.Add("3", "Springfield");

using(SqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString))
{
  bulkCopy.BulkCopyTimeout = 600; // in seconds
  bulkCopy.DestinationTableName = "state";
  bulkCopy.WriteToServer(table);
}