JDBC学习之JDBCUtils的编写

来源:互联网 发布:ppt数据图表 编辑:程序博客网 时间:2024/05/29 18:45
package cn.itcast.utils;


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 JdbcUtils {

private static Properties config = new Properties();
static{
try {
config.load(JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties"));
Class.forName(config.getProperty("driver"));
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}


public static Connection getConnection() throws SQLException{
return DriverManager.getConnection(config.getProperty("url"), config.getProperty("username"), config.getProperty("password"));
}


public static void release(Connection conn,Statement st,ResultSet rs){

if(rs!=null){
try{
rs.close();   //throw new 
}catch (Exception e) {
e.printStackTrace();
}
rs = null;
}
if(st!=null){
try{
st.close();
}catch (Exception e) {
e.printStackTrace();
}
st = null;
}
if(conn!=null){
try{
conn.close();
}catch (Exception e) {
e.printStackTrace();
}
}


}

}

我们需要将一些常用的代码或者说是函数写于工具类中,这样可以方便地使用。 本文中,我将一些数据库方面的信息,包括用户名、密码、数据库的链接存于配置文件中,所以在此类中需要读配置文件中的数据。

config.load(JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties"));
Class.forName(config.getProperty("driver"));

以上两句代码的作用是加载驱动,config.getProperty("driver")此可以获得数据库的地址,存于配置文件中,将这些信息存于配置文件中的好处是可以方便德修改时,方便得维护,比如将来需要改变数据库,只需要改配置文件即可。

DriverManager.getConnection(config.getProperty("url"), config.getProperty("username"), config.getProperty("password"));

此句代码返回connection对象,即我们所需要的,可以知道DriverManager是一个静态类,我们调用它的getConnection方法,参数分别为数据库的链接,数据库的用户名和数据库的密码。

工具类中还有一个释放资源的函数,此函数为模板函数,在哪里都可以用。最后必须要释放资源。