我尝试使用bulkCopy.WriteToServer()
将数据从远程SQL Server Express复制到本地SQL Server Express,但是没有数据写入我的本地SQL Server Express数据库。
代码立即跳过WriteToServer()
方法......我不知道它是否在内部失败并且没有显示错误消息
我已阅读How to duplicate a SQL Server 2000 table programatically using .NET 2.0?,我使用的代码非常相似。虽然我在远程和SQL Server 2014 Express本地使用SQL Server 2008 Express:
using (SqlConnection remoteConnection = new SqlConnection(remoteConnectionString))
{
var query = "SELECT * FROM information_schema.tables WHERE table_type = 'base table'";
SqlCommand commandGetTables = new SqlCommand(query, remoteConnection);
try
{
remoteConnection.Open();
SqlDataReader results = commandGetTables.ExecuteReader();
while (results.Read())
{
tables.Add(results.GetString(2));
}
results.Close();
}
catch (Exception ex)
{
//stuff
}
finally
{
remoteConnection.Close();
}
remoteConnection.Open();
foreach (var table in tables)
{
// Get data from the source table as a SqlDataReader.
var commandSourceData = new SqlCommand("SELECT * FROM " + table + ";", remoteConnection);
var reader = commandSourceData.ExecuteReader();
using (SqlConnection destinationConnection = new SqlConnection(destinationConnectionString))
{
destinationConnection.Open();
using (var bulkCopy = new SqlBulkCopy(destinationConnection))
{
bulkCopy.DestinationTableName = table;
try
{
// Write from the source to the destination.
bulkCopy.WriteToServer(reader);
}
catch (Exception ex)
{
//stuff
}
finally
{
//stuff removed for this post
}
}
}
}
remoteConnection.Close();
}
return true;
我知道这可能会受到SQL注入等的影响,但这个应用程序只供我使用,而不是这里的问题。
我做错了什么?
修改
我检查了读者的价值(var reader = commandSourceData.ExecuteReader();
)并且它有我想要的条目,这意味着他从遥控器上读的很好。
答案 0 :(得分:1)
bulkCopy.DestinationTableName = table;
bulkCopy.WriteToServer(reader);
这些行是错误的,它应该看起来像这样..
bulkCopy.DestinationTableName = "dbo." + DataTable.TableName;
bulkCopy.WriteToServer(DataTable);