Java連接PostgreSQL數據庫

felixilef 8年前發布 | 52K 次閱讀 Java

[Java]代碼    

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;

public class PG{
    public static void main(String []args){
        System.out.println("PostgreSQL JDBC...");
        try {
            Class.forName("org.postgresql.Driver");
        }catch (ClassNotFoundException e){
            System.out.println("could not find postgreSQL JDBC Driver");
            e.printStackTrace();
            return;
        }
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(
                    "jdbc:postgresql://localhost:5432/postgres", 
                    "postgres",
                    "");
        }catch (SQLException e){
            System.out.println("Connection Failed");
            e.printStackTrace();
            return;
        }

        if (connection != null){
            System.out.println("connect db successful!");
        }else {
            System.out.println("Failed to make conn!");
        }
        try {
            Statement  stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT 1 AS A");
            if(rs!=null){
                rs.next();
                System.out.println(rs.getInt("a"));
            }else {
                System.out.println("null");
            }
            rs.close();
            stmt.close();
            connection.close();
        }catch (Exception exp){
            exp.printStackTrace();
        }
    }
}
 本文由用戶 felixilef 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!