我们在写JDBC的时候,无论你使用什么的操作,你都先去连接数据,所有这里我们可以把数据的连接和关闭资源写一个工具类。
首先我们创建一个.properties的文件,放在src目录下。里面放的都是加载驱动和连接数据库的驱动。为什么要放在一个文件里面?因为你把这里属性写在代码中的话,那你去改的时候是不是很麻烦,这里面你可能会用到不同的数据库系统、数据库。
第一列:是加载驱动的属性,因为使用不用的数据区,加载驱动的方法也是不一样的。
第二列:jdbc:协议;
mysql:子协议(因为我用的是MySQL数据库)
//127.0.0.1:3306/:主机和端口号
db3:数据库
第三列:用户名
第四列:密码
代码实现:DBUtil.java
package com.qianfeng.util;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import com.mysql.jdbc.PreparedStatement;
public class DBUtil {
private static String driverClass;
private static String url;
private static String user;
private static String password;
//因为驱动只用加载一次,所有用静态代码块来写这一步
static{
//获取配置文件
Properties prop = new Properties();
//获取流文件
FileInputStream inStream = null;
try {
inStream = new FileInputStream("src/dbconfig.properties");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
prop.load(inStream);
} catch (IOException e1) {
e1.printStackTrace();
}
//获取所有属性值
driverClass = prop.getProperty("driverClass");
url = prop.getProperty("url");
user = prop.getProperty("user");
password = prop.getProperty("password");
//加载驱动
try {
Class.forName(driverClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/*
* 获取连接
*/
public static Connection getConnetion() throws SQLException{
return DriverManager.getConnection(url,user,password);
}
/*
* 关闭资源
*/
public static void closeAll(Connection conn,PreparedStatement ps,ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
我们发现,在用Properties对象获取属性的时候,要处理两次异常,是有点麻烦的.所有这里我们不用Properties对象去操作属性,而是用到ResourceBundle对象
将关于Properties对象的代码都删啦,换下如下代码:
//这个类的作用就是读取资源属性文件(properties),
ResourceBundle bundle = ResourceBundle.getBundle("dbconfig");
driverClass = bundle.getString("driverClass");
url = bundle.getString("url");
user = bundle.getString("user");
password = bundle.getString("password");
这里就不用处理异常了.但是我们在创建.properties文件的时候,一定要放在src目录下面.