以下所有处理都在本地机器上进行:
我有一个源数据库(在服务器上)和一个目标数据库(本地机器)。我有一个我希望从源复制到目标的表列表,即服务器--> 本地。
我首先使用简单的 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"];
}
}
}