用springboot 同步mysql 和SQL server两个数据库的代码可以写给我吗 使用yml文件
时间: 2024-05-02 22:17:41 浏览: 23
以下是使用Spring Boot和YAML文件配置同步MySQL和SQL Server数据库的示例代码:
1. 在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>8.4.0.jre11</version>
</dependency>
```
2. 在application.yml文件中配置MySQL和SQL Server的数据源:
```yaml
spring:
datasource:
mysql:
url: jdbc:mysql://localhost:3306/mysql_db?useSSL=false
username: root
password: root
sqlserver:
url: jdbc:sqlserver://localhost:1433;databaseName=sqlserver_db
username: sa
password: password
```
3. 创建一个名为DataSync的类,该类将执行从MySQL到SQL Server的数据同步。使用@Scheduled注释定期运行同步作业。以下是示例代码:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class DataSync {
@Autowired
private JdbcTemplate mysqlJdbcTemplate;
@Autowired
private JdbcTemplate sqlServerJdbcTemplate;
@Scheduled(fixedRate = 60000) // Run every minute
public void syncData() {
// Retrieve data from MySQL
List<Map<String, Object>> data = mysqlJdbcTemplate.queryForList("SELECT * FROM table");
// Insert data into SQL Server
data.forEach(row -> {
sqlServerJdbcTemplate.update("INSERT INTO table (column1, column2) VALUES (?, ?)",
row.get("column1"), row.get("column2"));
});
}
}
```
这将从MySQL中检索表数据,并将其插入到SQL Server中。同步作业将每分钟运行一次。
希望这可以帮助到您!
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)