将ADO.Net DataTable插入到SQL表中

3

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

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

我想一次性将数据表插入到 SQL 表中,而不需要迭代...

这可行吗,还是我要求过高了?


1
使用数据适配器,它会自动完成。 - garik
4个回答

11

您可以将整个DataTable作为单个表值参数传递,并一次性插入整个TVP。以下是来自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中提供。


3

我想你正在寻找SQLBulkCopy

(意思是:我认为您正在寻找SQLBulkCopy)

链接已失效。 - Noel

1
"

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。

0

您也可以尝试以下方法。

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");

                        }
                    }
                }
            }
        } 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接