java 連接 postgresql


      最近公司用postgresql這個數據庫,看網上說這個數據庫還算好用,自己就用了一下,我就是用java連接了一下數據庫。

     其實每個數據庫的連接方式大致相同,只是用到的驅動不同,用不同數據庫只需要換不同的數據庫驅動包。

   

  項目結構

  

 

代碼

DBHelper

 

package com.xxx.postgrepsql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

/**
 * 數據庫幫助類
 */
public class DBHelper {
    private static String url = "jdbc:postgresql://localhost:5432/Solution";
    private static String driver = "org.postgresql.Driver";
    private static String user = "postgres";
    private static String password = "18731362155";

    private Connection connection = null;

    public Connection getConnection() {
        return connection;
    }


    public PreparedStatement getStatement() {
        return statement;
    }


    private PreparedStatement statement = null;

    public DBHelper(String sql) {
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, user, password);
            statement = connection.prepareStatement(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void close() {
        try {
            this.connection.close();
            this.statement.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

jdbcDemo

package com.xxx.postgrepsql;

import java.sql.*;

/**
 * 連接postgres數據庫
 */
public class jdbcDemo {
    public static void main(String[] args) {
        String sql="select * from t_user";
        DBHelper dbHelper=new DBHelper(sql);
        try {
            ResultSet resultSet = dbHelper.getStatement().executeQuery();
            System.out.println("Id      username        password");
            while (resultSet.next()){
                System.out.println(resultSet.getString(1)+"          "+resultSet.getString(2)+"             "+resultSet.getString(3));
            }
            dbHelper.close();
        } catch (SQLException e) {
            dbHelper.close();
            e.printStackTrace();
        }

    }
}

 

 

如果有什么問題歡迎咨詢qq1058179540

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM