一般在开发的时候,数据库的连接信息通常写在配置文件中,包括xml文件或者properties文件。而不是在每次连接的时候都要读取配置获得connection,封装的方法有许多,这里只介绍一种,通过Properties类对配置文件进行操作,从而达到封装connection的目的。
好了,首先properties文件中是Oracle数据库的连接信息,具体如下
好了,接下来我写一个工厂类来读取配置文件,从而对connection进行封装。具体代码如下
返回connection后,就可以在dao层对数据库进行CRUD操作了。
好了,首先properties文件中是Oracle数据库的连接信息,具体如下
driver oracle.jdbc.OracleDriver
url jdbc:oracle:thin:@localhost:1521:orcl
user scott
password tiger
好了,接下来我写一个工厂类来读取配置文件,从而对connection进行封装。具体代码如下
package org.whatisjava.project1.sevice.impl;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
public class ConnectionFactory {
private static String url;
private static String driver;
private static String user;
private static String password;
static {
try {
Properties props = new Properties();
props.load(ConnectionFactory.class.getClassLoader()
.getResourceAsStream("db.properties")); //得到当前类的类加载器,以流的方式读取配置文件
driver = props.getProperty("driver");
url = props.getProperty("url");
user = props.getProperty("user");
password = props.getProperty("password");
Class.forName(driver); //加载驱动程序
} catch (Exception e) {
e.printStackTrace();
}
}
//返回Connection
public static Connection getConnection() throws Exception{
try {
Connection con = DriverManager.getConnection(url, user, password);
return con;
} catch (Exception e) {
return null;
}
}
}
返回connection后,就可以在dao层对数据库进行CRUD操作了。