用java编写pi数据库与mysql数据同步的脚本
时间: 2024-02-03 09:15:38 浏览: 106
以下是用 Java 编写 pi 数据库与 MySQL 数据库同步的脚本的示例代码:
```java
import java.sql.*;
public class SyncDB {
public static void main(String[] args) {
Connection piConn = null;
Connection mysqlConn = null;
try {
//连接 pi 数据库
String piUrl = "jdbc:pi://localhost:1234/mydb";
String piUser = "username";
String piPwd = "password";
piConn = DriverManager.getConnection(piUrl, piUser, piPwd);
//连接 MySQL 数据库
String mysqlUrl = "jdbc:mysql://localhost/mydb";
String mysqlUser = "username";
String mysqlPwd = "password";
mysqlConn = DriverManager.getConnection(mysqlUrl, mysqlUser, mysqlPwd);
//从 pi 数据库读取数据
Statement piStmt = piConn.createStatement();
ResultSet piRs = piStmt.executeQuery("SELECT * FROM mytable");
//插入或更新数据到 MySQL 数据库
PreparedStatement mysqlPStmt = null;
while (piRs.next()) {
int id = piRs.getInt("id");
String name = piRs.getString("name");
int age = piRs.getInt("age");
String sql = "INSERT INTO mytable (id, name, age) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE name=?, age=?";
mysqlPStmt = mysqlConn.prepareStatement(sql);
mysqlPStmt.setInt(1, id);
mysqlPStmt.setString(2, name);
mysqlPStmt.setInt(3, age);
mysqlPStmt.setString(4, name);
mysqlPStmt.setInt(5, age);
mysqlPStmt.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
//关闭连接
if (piConn != null) {
try {
piConn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (mysqlConn != null) {
try {
mysqlConn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
```
该脚本使用 JDBC 连接 pi 数据库和 MySQL 数据库,并使用 SQL 语句从 pi 数据库读取数据,然后将数据插入或更新到 MySQL 数据库。在插入数据时,使用 ON DUPLICATE KEY UPDATE 语句来处理重复的记录。请根据实际情况修改连接字符串、用户名、密码、数据库名称和表名称。
阅读全文