SqlBulkCopy WriteToServer方法在使用datatable时不写入任何数据

时间:2010-11-23 12:14:00

标签: c# sql sql-server sqlbulkcopy

所有以下处理都在localmachine上进行:

我有一个源数据库(在服务器上)和一个目标数据库(本地机器)。 我有一个表格列表,我希望从源代码复制到目的地,即服务器 - >本地。

我首先使用简单的SELECT *语句并使用Adpter.Fill(myDataTable)将来自服务器的所有数据存储在DataTable数组中,然后将myDataTable添加到DataTable数组中。

然后在本地我运行一个我在磁盘上的SQL脚本来删除本地数据库并重新创建它。使用[RightClick - >从SSMS获取脚本任务 - >生成脚本]

删除并重新创建本地数据库后,我使用SqlBulkCopy和前面的DataTable数组将服务器数据复制到新创建的本地数据库中。


问题是,在我点击SqlBulkCopy部分之前,一切都按预期工作。我没有例外,没有消息,也没有触发的bcp_SqlRowsCopied事件。数据根本没有被复制过......在这里发生什么,我至少会发现某种错误......


以下是控制台应用程序的完整代码: 请注意,它还没有生产就绪,因为还没有任何错误处理。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.IO;
using System.Diagnostics;

namespace TomboDBSync
{
    class Program
    {
        //Names of all the tables to copy from the server (the source) to our local db (the destination)
        public static string[] tables = new string[] {"br_Make_Model", "br_Model_Series", "br_Product_EngineCapacity", "br_Product_ProductAttributeDescription", "CompanyPassword", "dtproperties", "EngineCapacity", "Make", "Model", "PetrolType", "Product", "ProductAttribute", "ProductAttributeDescription", "ProductsImport", "ProductType", "Role", "SearchString", "Series", "Supplier", "Tally", "Transmission", "Users", "Year", "GRV"};


        static void Main(string[] args)
        {
            //Get Data from SourceDB
            DataTable[] dtTables = GetDataTables(tables);

            //Drop and Recreate Destination DB using SQL scripts
            DropAndRecreateDB();

            //Populate Destination with Data from SourceDB DataTables
            InsertDataFromDataTables(dtTables);
        }

        /// <summary>
        /// Takes all the data in the dtTables array which we got from the server (the source) and
        /// Bulk Copy it all into the local database (the destination)
        /// </summary>
        /// <param name="dtTables"></param>
        private static void InsertDataFromDataTables(DataTable[] dtTables)
        {
            foreach (DataTable dtTable in dtTables.ToList<DataTable>())
            {
                using (SqlBulkCopy bcp = new SqlBulkCopy(getLocalConnectionString(), SqlBulkCopyOptions.KeepIdentity & SqlBulkCopyOptions.KeepNulls))
                {
                    bcp.DestinationTableName = dtTable.TableName;

                    bcp.SqlRowsCopied += new SqlRowsCopiedEventHandler(bcp_SqlRowsCopied);
                    for (int colIndex = 0; colIndex < dtTable.Columns.Count; colIndex++)
                    {
                        bcp.ColumnMappings.Add(colIndex, colIndex);
                    }
                    bcp.WriteToServer(dtTable);

                }
             }                    
        }


        /// <summary>
        /// Row Copied eEvent handler for SqlBulkCopy
        /// </summary>
        static void bcp_SqlRowsCopied(object sender, SqlRowsCopiedEventArgs e)
        {
            Console.WriteLine("row written");
        }

        /// <summary>
        /// 1) Takes a list of tablenames.
        /// 2) Connects to the server (the source)
        /// 3) Does a SELECT * on all the tables and stick the results into DataTables
        /// </summary>
        /// <param name="tables"></param>
        /// <returns>Returns an array of DataTables with all the data from the server in them</returns>
        public static DataTable[] GetDataTables(string[] tables)
        {            
            //Query all the server tables and stick 'em into DataTables           
            DataTable[] dataTables = new DataTable[tables.Length];

            for (int tableIndex = 0; tableIndex < tables.Length; tableIndex++)
            {
                string qry = "SELECT * FROM " + tables[tableIndex] + ";";
                Console.Write(qry);
                DataTable dtTable = new DataTable();

                using (SqlConnection connection = new SqlConnection(getServerConnectionString()))
                {
                    if (connection.State != ConnectionState.Open) connection.Open();
                    using (SqlCommand cmd = new SqlCommand(qry, connection))
                    {
                        SqlDataAdapter adapter = new SqlDataAdapter();
                        adapter.SelectCommand = cmd;
                        adapter.Fill(dtTable);
                    }
                }
                dtTable.TableName = tables[tableIndex];
                dataTables[tableIndex] = dtTable;
                Console.WriteLine(" Rows: " + dtTable.Rows.Count);
            }
            return dataTables;
        }


        /// <summary>
        /// Parses and executes the script needed to drop and recreate the database
        /// </summary>
        private static void DropAndRecreateDB()
        {
            using (SqlConnection connection = new SqlConnection(getLocalConnectionString()))
            {
                string[] queries = getDropAndRecreateScript().Split(new string[] { "GO\r\n", "GO ", "GO\t" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string qry in queries)
                {
                    if (connection.State != ConnectionState.Open) connection.Open();
                    using (SqlCommand cmd = new SqlCommand(qry, connection))
                    {
                        cmd.ExecuteNonQuery();
                    }
                }
            }
        }

        /// <summary>
        /// Reads in the createdbscript.sql file from disk.
        /// It contains all the SQL statements needed to drop and recreate the database.
        /// </summary>
        /// <returns>SQL to drop and recreate the database</returns>

        public static string getDropAndRecreateScript()
        {
            string qry = "";
            StreamReader re = File.OpenText("createdbscript.sql");
            string input = null;
            while ((input = re.ReadLine()) != null)
            {
                qry += (" " + input + "\r\n"); 
            }
            Console.WriteLine(qry);
            re.Close();
            return qry;
        }

        public static string getServerConnectionString()
        {
            return ConfigurationManager.AppSettings["SOURCEDB"];
        }

        public static string getLocalConnectionString()
        {
            return ConfigurationManager.AppSettings["DESTINATIONDB"];
        }

    }
}

1 个答案:

答案 0 :(得分:6)

我已经尝试过你的代码,它为我成功复制了表格!

要启动SqlRowsCopied事件,您需要将bcp.NotifyAfter设置为某些&gt; 0值。

至于为什么你没有看到价值观,我不完全确定。如果数据库不在那里,你会得到一个例外(或者,至少,我做过)。我的代码中的一个区别是我注释掉DropAndRecreateDB(),当我在调试器中点击那一点时,我在SQL中手动运行了一个drop-create脚本并验证了表是否存在。

由于您发布的实际复制代码对我来说很好,我会仔细检查以确保您的连接字符串符合您的想法。如果您可以发布该信息,则可以更轻松地继续追踪。

更新

FWIW,这是我的drop / create脚本:

USE [master];
ALTER DATABASE MyTestDB2 SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
DROP DATABASE MyTestDB2;
GO
CREATE DATABASE MyTestDB2;
GO

USE [MyTestDB2];

CREATE TABLE [dbo].[tblPetTypes](
    [commonname] [nvarchar](50) NOT NULL,
    PRIMARY KEY CLUSTERED ([commonname])
)

CREATE TABLE [dbo].[tblPeople](
    [oid] [int] IDENTITY(1,1) NOT NULL,
    [firstname] [nvarchar](30) NOT NULL,
    [lastname] [nvarchar](30) NOT NULL,
    [phone] [nvarchar](30) NULL,
    PRIMARY KEY CLUSTERED ([oid])
)

CREATE TABLE [dbo].[tblPets](
    [oid] [int] IDENTITY(1,1) NOT NULL,
    [name] [nvarchar](50) NOT NULL,
    [pettype] [nvarchar](50) NULL,
    [ownerid] [int] NULL,
    PRIMARY KEY CLUSTERED ([oid])
) ON [PRIMARY]

...我在同一台服务器上从MyTestDB复制到MyTestDB2