怎样用JDBC连接PostgreSQL

2025-12-16 18:07:09
推荐回答(1个)
回答1:

首先必须要引入PostgreSQL的JDBC驱动;然后,类似这样来连接PostgreSQL:

package cmd01;
import java.sql.*;
public class Demo01 {
 public static void main(String[] args) {
  Connection  con = null;
  Statement  st = null;
  ResultSet  rs = null;
  
  try {
   Class.forName("org.postgresql.Driver");
   con = DriverManager.getConnection("jdbc:postgresql://localhost/adsTextile", "adsuser", "siprma");
   st = con.createStatement();
   rs = st.executeQuery("select 100 as val");
   while(rs.next()) {
    System.out.println("Value is: " + rs.getInt(1));
   }
   
   System.out.println("Hello World!");
  }
  catch (Exception e) {
   System.out.println("Exception: " + e.getMessage());
  }
  finally {
   if (rs != null) {
    try {
     rs.close();
    }
    catch (Exception e1) {     
    }
   }
   if (con != null) {
    try {
     con.close();
    }
    catch (Exception e0) {    
    }
    con = null;
   }
  }
 }
}