【问题标题】:Bulk Insert using QueryCommand object使用 QueryCommand 对象批量插入
【发布时间】:2015-08-05 06:27:40
【问题描述】:

有没有关于如何使用 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();
    }
}

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

【问题讨论】:

  • 通过这种方式,您的代码对我来说似乎很好。只是一个提示,由于您将表名作为输入,因此在将其放入 sql 查询之前,您需要提供强验证或使用包含有效表名的白名单。看起来你的 MY_TABLE 在每次迭代中都不会改变,你不需要每次都分配 CommandText 属性。只需您的foreach 之前对其进行评估,并在每次迭代时清除您的参数(就像您所做的那样)。
  • 我正在写 cmd.ExecuteNonQuery();在每次迭代中,它是在每次迭代时对数据库触发插入查询,还是收集所有信息然后触发插入查询?

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


【解决方案1】:

你可以使用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);
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多