抽取JDBC工具类
Posted wbyixx
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了抽取JDBC工具类相关的知识,希望对你有一定的参考价值。
package com.wbytts.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
public class JDBCUtils {
static String driverClass = null;
static String url = null;
static String name = null;
static String password = null;
static {
try {
//建立一个属性配置对象
Properties properties = new Properties();
//使用类加载器,去获取src底下的文件,要自己创建jdbc.properties配置文件
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
//Thread.currentThread().getContextClassLoader().getResourceAsStream("jdbc.properties");
//导入输入流
properties.load(is);
//读取属性
driverClass = properties.getProperty("driverClass");
url = properties.getProperty("url");
name = properties.getProperty("name");
password = properties.getProperty("password");
} catch (IOException e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName(driverClass);
conn = DriverManager.getConnection(url, name, password);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
/**
* 释放资源
* @param conn
* @param st
* @param rs
*/
public static void release(Connection conn, Statement st, ResultSet rs) {
closeRs(rs);
closeSt(st);
closeConn(conn);
}
public static void release(Connection conn, Statement st) {
closeSt(st);
closeConn(conn);
}
private static void closeRs(ResultSet rs) {
try {
if(rs != null) {
rs.close();
}
rs = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
rs = null;
}
}
private static void closeSt(Statement st) {
try {
if(st != null) {
st.close();
}
st = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
st = null;
}
}
private static void closeConn(Connection conn) {
try {
if(conn != null) {
conn.close();
}
conn = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
conn = null;
}
}
}
以上是关于抽取JDBC工具类的主要内容,如果未能解决你的问题,请参考以下文章