使用C#同步MSSQL和mysql数据库

时间:2014-07-09 07:18:59

标签: c# mysql sql-server

我在两台服务器上有两个数据库。一个是MSSQL,另一个是mysql。两个数据库中有两个相似的表。在更新MSSQL的那一刻,如何自动更新mysql?

2 个答案:

答案 0 :(得分:2)

您可以使用SQL Server CLR integration,创建一个更新MySQL的触发器。有一个Sync Data from SQL Server to MySQL example on Code Project作为起点。

答案 1 :(得分:0)

或者,您可以创建Linked Server

sysadmin群组成员的身份运行此脚本:

USE [master]
GO
EXEC master.dbo.sp_addlinkedserver 
    @server = N'MYSQL'
    , @srvproduct=N'MySQL'
    , @provider=N'MSDASQL'
    , @datasrc=N'MySQL'
    , @provstr=N'DRIVER={MySQL ODBC 5.1 Driver};SERVER=Server;PORT=3306;DATABASE=DBName; USER=user;PASSWORD=password;OPTION=3;'
    , @catalog=N'DatabaseName'

GO
EXEC master.dbo.sp_serveroption @server=N'MYSQL', @optname=N'collation compatible', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'MYSQL', @optname=N'data access', @optvalue=N'true'
GO
EXEC master.dbo.sp_serveroption @server=N'MYSQL', @optname=N'rpc', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'MYSQL', @optname=N'rpc out', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'MYSQL', @optname=N'connect timeout', @optvalue=N'0'
GO
EXEC master.dbo.sp_serveroption @server=N'MYSQL', @optname=N'collation name', @optvalue=null
GO
EXEC master.dbo.sp_serveroption @server=N'MYSQL', @optname=N'query timeout', @optvalue=N'0'
GO
EXEC master.dbo.sp_serveroption @server=N'MYSQL', @optname=N'use remote collation', @optvalue=N'true'
GO
USE [master]
GO
EXEC master.dbo.sp_addlinkedsrvlogin 
    @rmtsrvname = N'MYSQL'
    , @locallogin = NULL 
    , @useself = N'False'
    , @rmtuser = N'user'
    , @rmtpassword = N'password'
GO

然后在INSERT,DELETE和UPDATE上使用触发器来反映您在其他服务器上的更改。

例如,INSERT:

CREATE TRIGGER dbo.ti_MyTable
   ON  dbo.MyTable
   AFTER INSERT
AS 
BEGIN
    SET NOCOUNT ON;

    INSERT INTO MySql.Database..MyTable (column1, column2, column3)
    SELECT column1, column2, column3 FROM Inserted
END
GO