一、说明
在我们一般写数据库连接的程序中,经常用的是DriverManager接口来连接数据库。
好处:
1.直接用DriverManager.getConnection();连接数据库更为方便
2.可以同时管理多个驱动程序(即改变参数就可以实现连接不同的数据库)
二、实现
- 需要:
1.jdbc.properties 配置文件存放基本信息url,user,password
2.mysql或者其他数据库连接的jar包导入
3.写一个通用的方法
1.jdbc.properties1
2
3
4
5
6
7
8
9
10# 连接mysql数据库
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/dbname
user=root
password=123456
# 连接Oracle
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:dbname
user=scott
password=123456
3.通用方法1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23public Connection getConnection() throws Exception{
//创建Properties对象
Properties properties=new Properties();
//获取jdbc.properties对应的输入流
InputStream in=getClass().getClassLoader().getResourceAsStream("jdbc.properties");
//加载对应的输入流
properties.load(in);
//定义连接数据库所需的字符串,并获取配置文件中的值
String driverClass=null;
String user=null;
String password=null;
String url=null;
driverClass=properties.getProperty("driver");
user=properties.getProperty("user");
password=properties.getProperty("password");
url=properties.getProperty("url");
//加载数据库驱动程序
Class.forName(driverClass);
//返回数据库连接
return DriverManager.getConnection(url,user,password);
三、小结
这种方法虽然又优点正如上面所说,但也有缺点就是配置文件每次访问都要加载。为了解决这个问题我们需要。。。。。