连接数据库
在创建数据库连接之后,才能使用它来执行SQL语句操作数据。
函数原型
- DriverManager.getConnection(String url)
- DriverManager.getConnection(String url, Properties info)
- DriverManager.getConnection(String url, String user, String password)
参数
参数 |
描述 |
---|---|
url |
postgresql.jar数据库连接描述符。格式如下:
说明:
|
info |
数据库连接属性(所有属性大小写敏感)。常用的属性如下:
|
user |
数据库用户。 |
password |
数据库用户的密码。 |
![](https://support.huaweicloud.com/centralized-devg-v3-gaussdb/public_sys-resources/note_3.0-zh-cn.png)
uppercaseAttributeName参数开启后,如果数据库中有小写、大写和大小写混合的元数据,只能查询出小写部分的元数据,并以大写的形式输出。使用前请务必确认元数据的存储是否全为小写以避免数据出错。
示例
示例1:连接数据库
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
//以下代码将获取数据库连接操作封装为一个接口,可通过给定用户名和密码来连接数据库。 public static Connection getConnect(String username, String passwd) { //驱动类。 String driver = "org.postgresql.Driver"; //数据库连接描述符。 String sourceURL = "jdbc:postgresql://$ip:$port/postgres"; Connection conn = null; try { //加载驱动。 Class.forName(driver); } catch( Exception e ) { e.printStackTrace(); return null; } try { //创建连接。 conn = DriverManager.getConnection(sourceURL, username, passwd); System.out.println("Connection succeed!"); } catch(Exception e) { e.printStackTrace(); return null; } return conn; } |
示例2:使用Properties对象作为参数建立连接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
// 以下代码将使用Properties对象作为参数建立连接 public static Connection getConnectUseProp(String username, String passwd) { //驱动类。 String driver = "org.postgresql.Driver"; //数据库连接描述符。 String sourceURL = "jdbc:postgresql://$ip:$port/postgres"; Connection conn = null; Properties info = new Properties(); try { //加载驱动。 Class.forName(driver); } catch( Exception e ) { e.printStackTrace(); return null; } try { info.setProperty("user", username); info.setProperty("password", passwd); //创建连接。 conn = DriverManager.getConnection(sourceURL, info); System.out.println("Connection succeed!"); } catch(Exception e) { e.printStackTrace(); return null; } return conn; } |
常用参数详情请参见JDBC常用参数参考。