开发者

Insert ADO.Net DataTable into an SQL table

The current solution i implemented is awful!

I use a for... loop for inserting records from an ADO.NET data-table into an SQL table.

I would like to insert at once the data-tab开发者_如何学Cle into the SQL table, without iterating...

Is that possible, or am i asking too much?


You can pass the entire DataTable as a single Table Valued Parameter and insert the entire TVP at once. The following is the example from 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 are only available in SQL 2008.


I think you are looking for SQLBulkCopy.


SqlBulkCopy is the simplest solution.

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

You can create SqlBulkCopyColumnMapping if the columns in your DataTable don't match your database table.


You can also try the following method.

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

                        }
                    }
                }
            }
        } 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜