最近公司用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
时间: 2024-09-30 11:11:13