一、说明
Java可以通过驱动Driver获取数据库连接,这里通过配置文件解耦的方式来实现一个方法连接不同的数据库。
- 需要:
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
23
24
25public Connection getConnection()throws Exception{
String driverClass=null;
String user=null;
String password=null;
String url=null;
//读取文件
InputStream in=getClass().getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties=new Properties();
properties.load(in);
driverClass=properties.getProperty("driver");
user=properties.getProperty("user");
password=properties.getProperty("password");
url=properties.getProperty("url");
Driver driver=(Driver)Class.forName(driverClass).newInstance();//反射机制导入驱动
Properties info=new Properties();
info.put("user",user);
info.put("password",password);
Connection conn=driver.connection(url,info);
return conn;
}
二、小结
知道如何加载配置文件,以及如何用Driver连接数据库。一般不用Driver来链接数据库,这是给数据库厂商用的,一般程序中用DriverManager。