您的位置:首页 > 数据库

jdbc 链接数据库工具类

2015-06-25 13:39 323 查看
package com.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
/**
* jdbc 链接数据库工具类
* @author Administrator
*
*/
public class DBUtils {
private static Properties props = new Properties();
static{
InputStream is = null;
is = DBUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
try {
props.load(is);
} catch (IOException e) {
e.printStackTrace();
} finally{
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 获得连接
* @return conn
*/
public static Connection createConn(){
Connection conn = null;
try {
Class.forName((String)props.get("driver"));
//ip地址 + 数据库名称
conn = DriverManager.getConnection(
(String)props.get("url"),
(String)props.get("username"),
(String)props.get("password")
);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
/**
* 编译执行
* */
public static PreparedStatement getPs(Connection conn , String sql){
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return ps ;
}
/**
* 关闭连接
* @param conn
*/
public static void close(Connection conn){
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(ResultSet rs){
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(PreparedStatement ps){
if(ps != null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: