0

以下所有处理都在本地机器上进行:

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

我首先使用简单的 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"];
        }

    }
}
4

1 回答 1

6

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

为了让SqlRowsCopied事件触发,您需要设置bcp.NotifyAfter一些 > 0 的值。

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

由于您发布的实际复制代码对我来说很好,因此我会仔细检查以确保您的连接字符串是您认为的那样。如果您可以发布该信息,则继续追踪会更容易。

更新:

FWIW,这是我的删除/创建脚本:

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

于 2010-11-23T15:16:43.423 回答