如何将远程服务器数据库与本地数据库同步

far*_*med 2 .net c# asp.net sql-server-2008

我想从远程服务器数据库到本地数据库,在
页面加载事件或其他一些好的方法中获取单个表的所有细节,这应该发生在后端进程可以帮助我解决这个问题.

1.在桌面和Web应用程序中创建单个应用程序.
2.当User在Desktop Application中注册新客户时,应在启动应用程序时在Web Application Db中添加新客户.

注意:

服务器数据库表列可能与本地数据库略有不同.每次在服务器中添加新用户时,它应该在加载UserPage.aspx页面时更新本地数据库.

工具使用: ASP.NET,SQL SERVER 2008.

例如: 让DB名称为样本,表名称为customer

Table Header in Server DB: Cus_id,Cus_name,Cus_address,Cus_email,Cus_mob,Link_Id
Table Headers in Local DB: Cus_id,Cus_name,Cus_address,Cus_email,Cus_mob,Cus_password,Link_Id
Run Code Online (Sandbox Code Playgroud)

这里Link_id用作桌面和Web应用程序的通用..最初在Web应用程序中,
当添加新用户时,除了
Link_id之外,所有数据都存储在DB中,这是从服务器获取的响应并保存在本地D B.

谢谢.

Pat*_*man 7

我会推荐这种方法:

  1. 在本地数据库中创建一个临时表;
  2. 在更改需要同步的表时,在本地数据库中创建一个触发器;
  3. 更新登台表;
  4. 偶尔将登台表与服务器同步(每分钟一小时/每天一次,具体取决于您的需要);

    A)在本地数据库中创建链接数据库连接.创建一个过程,将登台表中的数据同步到服务器数据库;

    B)或者通过读取本地数据库并写入服务器数据库,使用ASP.NET同步数据库.

这个解决方案比在ASP.NET中直接执行更好,因为当您的服务器出现可用性问题时,这仍然有效.

一个完整的工作示例:

create table x
( id          numeric(18, 0) identity(1,1)  not null
, description nvarchar(1000)                not null
)
go

create table x_staging
( id          numeric(18, 0) not null
, description nvarchar(1000) not null
, synced      bit            not null default 0
)
go

/*
 * create this one on remote server in a database called test

create table remote_table
( id          numeric(18, 0) identity(1,1)  not null
, source_id   numeric(18, 0)                not null
, description nvarchar(1000)                not null
)
go
*/

create trigger x_ori on x
after insert
as
begin
  insert into x_staging
  ( id
  , description
  , synced
  )
  select id
  ,      description
  ,      0 -- false
  from   inserted
  ;
end
go

create procedure sync
as
begin
  declare @id numeric(18,0)
  declare @description nvarchar(1000)
  declare @x_cursor cursor

  set     @x_cursor = cursor for
  select  id
  ,       description
  from    x_staging

  open    @x_cursor
  fetch next
  from  @x_cursor into @id, @description
  while @@fetch_status = 0
  begin
    insert
    into   [REMOTE_SERVER].test.dbo.remote_table
    ( source_id
    , description
    )
    values
    ( @id
    , @description
    )
    ;
    update x_staging
    set    synced = 1
    where  id = @id
    ;
  fetch next
  from @x_cursor into @id, @description
  end

  close @x_cursor
  deallocate @x_cursor
end
go

insert
into   x
( description
)
values
( 'test'
)
go

begin
  exec sync;
end
Run Code Online (Sandbox Code Playgroud)

调用sync将执行同步.请注意remote_table在另一台服务器上创建并创建数据库链接.