简体   繁体   English

将整个表从SQL Server CE数据库复制到另一个表

[英]Copy a whole table from a SQL Server CE database to another

I'm developing a C# application and I want to copy a whole table from a SQL Server CE database to another programmatically. 我正在开发C#应用程序,我想以编程方式将整个表从SQL Server CE数据库复制到另一个数据库。 I know I can use this command in SQL Server, but I'm not sure how to use two database connections in one query in C#. 我知道我可以在SQL Server中使用此命令,但是我不确定如何在C#中的一个查询中使用两个数据库连接。

Select * into DestinationDB.dbo.tableName from SourceDB.dbo.SourceTable

Thanks in advance. 提前致谢。

You wouldn't do it the same way as in SQL Server because there's no single server that manages both databases. 您不会像在SQL Server中那样进行此操作,因为没有单个服务器可以同时管理两个数据库。 Your app is the only thing that links the two databases so the the data has to go through your app. 您的应用程序是链接两个数据库的唯一内容,因此数据必须通过您的应用程序。 You're trying to do it the wrong way and that's why you can't find a solution: you're looking for the wrong thing. 您正在尝试以错误的方式进行操作,这就是为什么找不到解决方案的原因:您正在寻找错误的内容。

There are examples of this out there. 这里有一些例子。 I know, because I've written more than one myself. 我知道,因为我自己写的不止一个。 You simply need to use a data adapter to populate a DataTable from the first database and then a data adapter to save the contents of that DataTable to the second database. 你只需要使用数据适配器来填充DataTable从第一数据库,然后数据适配器到的内容保存DataTable到第二个数据库。 If the data sources are the same type then you can even use just one data adapter because the SelectCommand and InsertCommand can have different connections. 如果数据源是同一类型,则您甚至可以只使用一个数据适配器,因为SelectCommandInsertCommand可以具有不同的连接。

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);
}

That example uses SqlClient but it works the same for any provider, including SqlServerCe. 该示例使用SqlClient,但对包括SqlServerCe在内的任何提供程序都起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM