简体   繁体   中英

Export table from Postgres database(on server) to csv file(on local) in java

I would like to export a table from the database to CSV file on my local machine. Now, I can connect to the database and display all the elements in the console with System.out.println(). But I want to redirect these elements in a csv file. Please help.

    //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

Use PgJDBC's CopyManager , which you obtain from the PGConnection you can cast a java.sql.Connection for a PgJDBC connection to.

If you use a connection pool you might need to find out how to unwrap the proxied Connection to get the real underlying PgJDBC Connection object.

CopyManager supports COPY ... TO STDOUT , allowing you to stream server-generated CSV data to the client application.

取决于情况,但是您可能需要编写一个带有网页的Web应用程序,该网页的响应包含.csv文件和Content-Type响应标头为“ text / csv”

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM