使用JDBC連接資料庫的範例,先準備連結 postgresql 需要的 jar檔(postgresql-8.4-701.jdbc4.jar)

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
public class ConnToPostgresql {
    //show all tables in database
    public static String COMM_SHOW_ALLTABLES = "select * from information_schema.tables" +
            " where table_schema not in ('information_schema','pg_catalog')";
    //show all databases
    public static String COMM_SHOW_ALLDATABASE = "select * from pg_database";
    //show size of databases(pg_database_size() support PostgreSQL 8.1)
    public static String COMM_SHOW_DB_SIZE = "SELECT pg_database.datname," +
            " pg_size_pretty(pg_database_size(pg_database.datname)) AS size" +
            " FROM pg_database;";
    Connection conn;
    String driver = "org.postgresql.Driver";
    String url;
    String ipNum;
    String portNum;
    String dbName;
    String userName;
    String passWord;
    public ConnToPostgresql(String ipnum,String portnum,
            String dbname,String username,String password){
        ipNum = ipnum;
        portNum = portnum;
        dbName = dbname;
        userName = username;
        passWord = password;
        try {
            Class.forName(driver);
            // String url = "jdbc:postgresql://localhost:5432/test1225";
            url = "jdbc:postgresql://" + ipNum + ":" + portNum + "/"
                    + dbName;
            try {
                if (userName == null && passWord == null) {
                    conn = DriverManager.getConnection(url);
                } else {
                    conn = DriverManager.getConnection(url, userName, passWord);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public Connection getConn(){
        return conn;
    }
}

只要建立 ConnToPostgresql 物件,在建構子中傳入帳號和密碼,就能建立和資料庫連線