JDBC是java中为了和数据库进行交流而开发的一套数据库规范,以下工具类用于灵活的产生数据库连接和安全的释放数据库连接
程序使用的Mysql,但对于其他的数据库只需要改变配置文件即可使用
JDBCFactory.java
package com.jdbc.jdbc;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JDBCFactory {
//定义连接数据库所需要的字段
private static String driveClassName = null;
private static String url = null;
private static String username = null;
private static String password = null;
//通过配置文件为以上字段赋值
static{
try {
InputStream in = JDBCFactory.class.getClassLoader().getResourceAsStream("dbcfg.properties");
Properties prop = new Properties();
prop.load(in);
driveClassName = prop.getProperty("className");
url = prop.getProperty("url");
username = prop.getProperty("username");
password = prop.getProperty("password");
//加载驱动类
Class.forName(driveClassName);
} catch (Exception e) {
throw new RuntimeException("Can't find the properties!");
}
}
//得到连接
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,username,password);
}
//释放资源
public static void release(ResultSet rs,Statement stmt,Connection conn) {
if(rs != null) {
try{
rs.close();
}catch(Exception e){} //ignore
rs = null;
}
if(stmt != null) {
try{
stmt.close();
}catch(Exception e){} //ignore
stmt = null;
}
if(conn != null) {
try {
conn.close();
}catch(Exception e){} //ignore
}
}
}
dbcfg.properties
className=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/[数据库名称]?userUnicode=true&characterEncoding=utf-8
username=[数据库用户名]
password=[数据库密码]