如何使用 Replication 对象创建 SQL Server Compact Edition 数据库(以编程方式)
本主题将介绍如何以编程方式调用 SqlServerCe.Replication 对象的 AddSubscription 方法来创建 Microsoft SQL Server 2005 Compact Edition (SQL Server Compact Edition) 数据库。有关使用 SqlServerCe 命名空间的详细信息,请参阅 SqlServerCe 命名空间参考文档。
使用 Replication 对象创建 SQL Server Compact Edition 数据库
初始化新的 Replication 对象。
SqlCeReplication repl = new SqlCeReplication();
设置 Replication 对象的属性。这些属性可以包括连接到 SQL Server 发布服务器所需的信息。SubscriberConnectionString 属性指定将创建的数据库的文件名和位置。
repl.SubscriberConnectionString = "Data Source=MyDatabase.sdf"; repl.InternetUrl = "https://www.adventure-works.com/" + "sqlmobile/sqlcesa30.dll"; repl.InternetLogin = "MyInternetLogin"; repl.InternetPassword = "<password>"; repl.Publisher = "MyPublisher"; repl.PublisherDatabase = "MyPublisherDatabase"; repl.PublisherLogin = "MyPublisherLogin"; repl.PublisherPassword = "<password>"; repl.Publication = "MyPublication"; repl.Subscriber = "MySubscriber";
调用 AddSubscription 方法,传入 AddOption.CreateDatabase 参数。
repl.AddSubscription(AddOption.CreateDatabase);
示例
此示例说明创建新数据库的步骤:创建 Replication 对象,设置数据库和订阅的属性,然后调用 AddSubscription 方法。
SqlCeReplication repl = null;
try
{
// Instantiate and configure SqlCeReplication object
//
repl = new SqlCeReplication();
repl.InternetUrl = "https://www.adventure-works.com/sqlmobile/sqlcesa30.dll";
repl.InternetLogin = "MyInternetLogin";
repl.InternetPassword = "<password>";
repl.Publisher = "MyPublisher";
repl.PublisherDatabase = "MyPublisherDatabase";
repl.PublisherLogin = "MyPublisherLogin";
repl.PublisherPassword = "<password>";
repl.Publication = "MyPublication";
repl.Subscriber = "MySubscriber";
repl.SubscriberConnectionString = "Data Source=MyDatabase.sdf";
// Create a local SQL Server Compact Edition Database subscription
//
repl.AddSubscription(AddOption.CreateDatabase);
// Synchronize to the SQL Server database
//
repl.Synchronize();
}
catch (SqlCeException)
{
// Handle errors here
//
}
finally
{
// Dispose the repl object
//
repl.Dispose();
}
Dim repl As SqlCeReplication = Nothing
Try
' Instantiate and configure SqlCeReplication object
'
repl = New SqlCeReplication()
repl.InternetUrl = "https://www.adventure-works.com/sqlmobile/sqlcesa30.dll"
repl.InternetLogin = "MyInternetLogin"
repl.InternetPassword = "<password>"
repl.Publisher = "MyPublisher"
repl.PublisherDatabase = "MyPublisherDatabase"
repl.PublisherLogin = "MyPublisherLogin"
repl.PublisherPassword = "<password>"
repl.Publication = "MyPublication"
repl.Subscriber = "MySubscriber"
repl.SubscriberConnectionString = "Data Source=MyDatabase.sdf"
' Create the local SQL Server Compact Edition Database subscription
'
repl.AddSubscription(AddOption.CreateDatabase)
' Synchronize to the SQL Server to populate the subscription
'
repl.Synchronize()
Catch
' Handle errors here
'
Finally
' Dispose the repl object
'
repl.Dispose()
End Try