javaWeb_JDBC_DriverManager接口


JDBC基础_driverManager接口mysql

1.使用DriverManager进行数据库链接

(1).实现步骤
1. 准备链接数据库的 4 个字符串.
driverClass:数据库驱动的全类名
jdbcUrl:数据库中使用存在的数据库表以及对应的数据库链接信息
uer:数据库用户名
password:数据库密码sql

2. 加载数据库驱动程序(对应的 Driver 实现类中有注册驱动的静态代码块.)
好处:这里面使用的DirverManager能够加载多个相同或者是不一样的数据库驱动。

3. 经过 DriverManager 的 getConnection() 方法获取数据库链接.数据库


(2).代码测试

public void testDriverManager() throws Exception{
//1. 准备链接数据库的 4 个字符串.
//驱动的全类名.
String driverClass = "com.mysql.jdbc.Driver";
//JDBC URL
String jdbcUrl = "jdbc:mysql:///test";
//user
String user = "root";
//password
String password = "123456";

//2. 加载数据库驱动程序(对应的 Driver 实现类中有注册驱动的静态代码块.)
Class.forName(driverClass);

//3. 经过 DriverManager 的 getConnection() 方法获取数据库链接.
Connection connection =
DriverManager.getConnection(jdbcUrl, user, password);
System.out.println(connection);

}测试


(3).使用DriverManager的好处
1). 能够经过重载的 getConnection() 方法获取数据库链接. 较为方便
2). 能够同时管理多个驱动程序: 若注册了多个数据库链接, 则调用 getConnection()
方法时传入的参数不一样, 即返回不一样的数据库链接。 this

 

(4).使用DriverManager获取数据库链接2(读取配置文件的方式)

A:配置文件省略

B:测试代码:

public Connection getConnection2() throws Exception{
//1. 准备链接数据库的 4 个字符串.

//1). 建立 Properties 对象
Properties properties = new Properties();

//2). 获取 jdbc.properties 对应的输入流
InputStream in =
this.getClass().getClassLoader().getResourceAsStream("jdbc.properties");

//3). 加载 2) 对应的输入流
properties.load(in);

//4). 具体决定 user, password 等4 个字符串.
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String jdbcUrl = properties.getProperty("jdbcUrl");
String driver = properties.getProperty("driver");

//2. 加载数据库驱动程序(对应的 Driver 实现类中有注册驱动的静态代码块.)
Class.forName(driver);

//3. 经过 DriverManager 的 getConnection() 方法获取数据库链接.
return DriverManager.getConnection(jdbcUrl, user, password);
}对象

相关文章
相关标签/搜索