postgresql 去重后写入数据库表,请用java写代码实现
时间: 2023-03-19 17:22:01 浏览: 110
以下是使用 Java 语言将去重后的数据写入 PostgreSQL 数据库表的代码示例:
```java
import java.sql.*;
import java.util.*;
public class PostgresDistinctInsert {
public static void main(String[] args) throws SQLException {
String url = "jdbc:postgresql://localhost/mydb";
String user = "myuser";
String password = "mypassword";
Connection connection = null;
PreparedStatement statement = null;
try {
// 连接数据库
connection = DriverManager.getConnection(url, user, password);
// 执行 SQL 语句,获取去重后的数据
String distinctQuery = "SELECT DISTINCT column1, column2, column3 FROM mytable";
Statement distinctStatement = connection.createStatement();
ResultSet resultSet = distinctStatement.executeQuery(distinctQuery);
// 准备插入语句
String insertQuery = "INSERT INTO myothertable (column1, column2, column3) VALUES (?, ?, ?)";
statement = connection.prepareStatement(insertQuery);
// 遍历结果集,将每行数据插入到目标表中
while (resultSet.next()) {
String column1Value = resultSet.getString("column1");
int column2Value = resultSet.getInt("column2");
Date column3Value = resultSet.getDate("column3");
statement.setString(1, column1Value);
statement.setInt(2, column2Value);
statement.setDate(3, column3Value);
statement.executeUpdate();
}
System.out.println("数据插入成功!");
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭连接和语句对象
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
}
}
}
```
以上代码使用 JDBC 连接 PostgreSQL 数据库,首先执行一个带有 DISTINCT 关键字的 SQL 查询语句,获取去重后的数据集。然后,使用预编译的 INSERT 语句将每行数据插入到目标表中。最后,关闭连接和语句对象。