【问题标题】:Insert ADO.Net DataTable into an SQL table将 ADO.Net DataTable 插入 SQL 表
【发布时间】:2010-03-18 17:50:40
【问题描述】:

我目前实施的解决方案很糟糕!

我使用for... loop 将记录从 ADO.NET 数据表插入到 SQL 表中。

我想立即将数据表插入 SQL 表中,而不进行迭代...

这可能吗,还是我要求太多了?

【问题讨论】:

  • 使用dataAdapter,它会自己做。

标签: asp.net sql-server ado.net insert bulkinsert


【解决方案1】:

您可以将整个 DataTable 作为单个表值参数传递并一次插入整个 TVP。以下是来自Table-Valued Parameters in SQL Server 2008 (ADO.NET)的例子:

// Assumes connection is an open SqlConnection.
using (connection)
{
// Create a DataTable with the modified rows.
DataTable addedCategories = CategoriesDataTable.GetChanges(
    DataRowState.Added);

// Define the INSERT-SELECT statement.
string sqlInsert = 
    "INSERT INTO dbo.Categories (CategoryID, CategoryName)"
    + " SELECT nc.CategoryID, nc.CategoryName"
    + " FROM @tvpNewCategories AS nc;"

// Configure the command and parameter.
SqlCommand insertCommand = new SqlCommand(
    sqlInsert, connection);
SqlParameter tvpParam = insertCommand.Parameters.AddWithValue(
    "@tvpNewCategories", addedCategories);
tvpParam.SqlDbType = SqlDbType.Structured;
tvpParam.TypeName = "dbo.CategoryTableType";

// Execute the command.
insertCommand.ExecuteNonQuery();
}

TVP 仅在 SQL 2008 中可用。

【讨论】:

    【解决方案2】:

    我想你正在寻找SQLBulkCopy

    【讨论】:

    • 链接不再有效
    【解决方案3】:

    你也可以试试下面的方法。

    private void button1_Click(object sender, EventArgs e)
    {
        tabevent();
        DataSet ds = new DataSet();
        DataTable table = new DataTable("DataFromDGV");
    
        ds.Tables.Add(table);
    
        foreach (DataGridViewColumn col in dataGridView1.Columns)
            table.Columns.Add(col.HeaderText, typeof(string));
    
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            table.Rows.Add(row);
            foreach (DataGridViewCell cell in row.Cells)
            {
    
                        table.Rows[row.Index][cell.ColumnIndex] = cell.Value;
                    }
                }
    
                // DataTable ds1changes = ds1.Tables[0].GetChanges();
                if (table != null)
                {
                    SqlConnection dbConn = new SqlConnection(@"Data Source=wsswe;Initial Catalog=vb;User ID=sa;Password=12345");
                    SqlCommand dbCommand = new SqlCommand();
                    dbCommand.Connection = dbConn;
                    foreach (DataRow row in table.Rows)
                    {
                        if (row["quantity"] != null && row["amount"]!=null && row["itemname"]!=null)
                        {
                            if (row["amount"].ToString() != string.Empty)
                            {
                                dbCommand.CommandText =
                                "INSERT INTO Bill" +
                                "(Itemname,Participants,rate,Quantity,Amount)" +
                                "SELECT '" + Convert.ToString(row["itemname"]) + "' AS Itemname,'" + Convert.ToString(row["Partcipants"]) + "' AS Participants,'" + Convert.ToInt32(row["rate"]) + "' AS rate,'" +
                                 Convert.ToInt32(row["quantity"]) + "' AS Quantity,'" + Convert.ToInt32(row["amount"]) + "' AS Amount";
    
    
                                dbCommand.Connection.Open();
                                dbCommand.ExecuteNonQuery();
    
                                if (dbCommand.Connection.State != ConnectionState.Closed)
                                {
                                    dbCommand.Connection.Close();
                                }
    
                                MessageBox.Show("inserted");
    
                            }
                        }
                    }
                }
            } 
    

    【讨论】:

      【解决方案4】:

      SqlBulkCopy 是最简单的解决方案。

              using (SqlConnection dbConn = new SqlConnection(connectionString))
              {
                  dbConn.Open();
                  using (SqlBulkCopy bulkCopy = new SqlBulkCopy(dbConn))
                  {
                      bulkCopy.DestinationTableName =
                          "dbo.MyTable";
                      try
                      {
                          bulkCopy.WriteToServer(myDataTable, DataRowState.Added);
                      }
                      catch (Exception ex)
                      {
                          myLogger.Error("Fail to upload session data. ", ex);
                      }
                  }
              }
      

      如果 DataTable 中的列与数据库表不匹配,您可以创建 SqlBulkCopyColumnMapping。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-07
        • 1970-01-01
        • 2011-08-29
        • 2016-01-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多