標籤:font man style 分享 ret 技術分享 use import 驅動
最近公司用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
java 串連 postgresql