[英]Export table from Postgres database(on server) to csv file(on local) in java
我想将数据库中的表导出到本地计算机上的CSV文件中。 现在,我可以连接到数据库,并使用System.out.println()在控制台中显示所有元素。 但是我想将这些元素重定向到一个csv文件中。 请帮忙。
//STEP 1. Import required packages
import java.sql.*;
public class ExportDataToCSV {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "org.postgresql.Driver";
static final String DB_URL = "jdbc:postgresql://[localhost]:54432/database";
// Database credentials
static final String USER = "login";
static final String PASS = "pwd";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("org.postgresql.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, age, first, last FROM table";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
String id = rs.getString("id");
String age = rs.getString("age");
String first = rs.getString("first");
String last = rs.getString("age");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 5: Clean-up environment
rs.close();
stmt.close();
conn.close(); }catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace(); }catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace(); }finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try }//end try }//end main }//end FirstExample
使用从PGConnection
获得的PgJDBC的CopyManager
,可以将java.sql.Connection
强制转换为PgJDBC连接。
如果使用连接池,则可能需要了解如何解开代理的Connection
以获得真正的基础PgJDBC Connection对象。
CopyManager
支持COPY ... TO STDOUT
,使您可以将服务器生成的CSV数据流式传输到客户端应用程序。
取决于情况,但是您可能需要编写一个带有网页的Web应用程序,该网页的响应包含.csv文件和Content-Type响应标头为“ text / csv”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.