更新时间:2025-10-23 GMT+08:00
以常规方式连接
以下2个示例分别采用DriverManager.getConnection(String url, String user, String password)和DriverManager.getConnection(String url, Properties info)方法,以不加密方式(即常规方式)创建数据库连接。
示例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 = "com.mysql.jdbc.Driver"; //数据库连接描述符。 String sourceURL = "jdbc:mysql://$ip:$port/database?useSSL=false&allowPublicKeyRetrieval=true"; 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 = "com.mysql.jdbc.Driver"; //数据库连接描述符。 String sourceURL = "jdbc:mysql://$ip:$port/database?useSSL=false&allowPublicKeyRetrieval=true"; 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; } |
父主题: 连接数据库