我正在开发一个C#应用程序,我希望以编程方式将整个表从SQL Server CE数据库复制到另一个。我知道我可以在SQL Server中使用此命令,但我不确定如何在C#中的一个查询中使用两个数据库连接。
Select * into DestinationDB.dbo.tableName from SourceDB.dbo.SourceTable
提前致谢。
答案 0 :(得分:0)
您不会像在SQL Server中那样执行此操作,因为没有单个服务器可以管理这两个数据库。您的应用程序是唯一链接两个数据库的应用程序,因此数据必须通过您的应用程序。你试图以错误的方式去做,这就是为什么你找不到解决办法的原因:你正在寻找错误的东西。
有这方面的例子。我知道,因为我自己写了不止一本。您只需使用数据适配器从第一个数据库填充DataTable
,然后使用数据适配器将DataTable
的内容保存到第二个数据库。如果数据源类型相同,那么您甚至可以只使用一个数据适配器,因为SelectCommand
和InsertCommand
可以有不同的连接。
using (var adapter = new SqlDataAdapter("SELECT statement here", "source connection string here"))
using (var destinationConnection = new SqlConnection("destination connection string here"))
using (var insertCommand = new SqlCommand("INSERT statement here", destinationConnection))
{
// Add parameters to insertCommand here.
adapter.InsertCommand = insertCommand;
// Leave the RowState of all DataRows as Added so they are ready to be inserted.
adapter.AcceptChangesDuringFill = false;
var table = new DataTable();
// Retrieve data from source and save to destination.
adapter.Fill(table);
adapter.Update(table);
}
该示例使用SqlClient,但它对任何提供程序都有效,包括SqlServerCe。