C# 把一个DT内的数据 批量插入到数据库里(SQL server 2005)

 private static void DataTableToSQLServer(DataTable dt)
        {
            string connectionString = "";//GetConnectionString();  

            using (SqlConnection destinationConnection = new SqlConnection(connectionString))
            {
                destinationConnection.Open();

                using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destinationConnection))
                {
                    try
                    {
                        bulkCopy.DestinationTableName = "table_name";//要插入的表的表明   
                        bulkCopy.ColumnMappings.Add("feild1", "feild1");//映射字段名 DataTable列名 ,数据库 对应的列名   
                        bulkCopy.ColumnMappings.Add("feild2", "feild2");
                        /*...
                         * ...
                         * ...
                         * ...
                         * ...*/
                        bulkCopy.WriteToServer(dt);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        /* Close the SqlDataReader. The SqlBulkCopy   
                         object is automatically closed at the end   
                         of the using block.*/
                    }
                }
            }
        }

 

posted @ 2013-10-28 14:26  JasonGu0  阅读(671)  评论(0编辑  收藏  举报