【JDBC】Extra03 PostgreSQL-JDBC
PostgreSQL的JDBC实现:
<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql --> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>42.2.14</version> </dependency>
连接Demo:
public static void originConnection() throws SQLException { Connection connection = null; try { Class.forName("org.postgresql.Driver"); connection = DriverManager.getConnection( "jdbc:postgresql://127.0.0.1:5432/db01", "postgres", "123456" ); System.out.println(connection); } catch (Exception e) { e.printStackTrace(); System.err.println(e.getClass().getName()+": "+e.getMessage()); System.exit(0); } finally { connection.close(); } // System.out.println("Opened database successfully"); }
封装工具类:
package cn.echo42.util; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; /** * @author DaiZhiZhou * @file PostgreSQL-Connector * @create 2020-07-25 23:40 */ public class PdbcUtil { private static Properties properties; static { try { properties = new Properties(); InputStream inputStream = PdbcUtil.class.getClassLoader().getResourceAsStream("pdbc.properties"); properties.load(inputStream); Class.forName(properties.getProperty("driver")); } catch (Exception exception) { exception.printStackTrace(); } } public static Connection getConnection(){ try { return DriverManager.getConnection( properties.getProperty("url"), properties.getProperty("user"), properties.getProperty("password") ); } catch (SQLException sqlException) { sqlException.printStackTrace(); } return null; } }
配置文件:
driver = org.postgresql.Driver url = jdbc:postgresql://49.234.116.100:5432/db01 user = postgres password = 123456
感觉和MySQL的Jdbc是完全一样的,只需要更换对应的配置信息和驱动包即可,程序的连接对象获取一样