package com.iok.jee.dbc;
import com.mysql.jdbc.*;
import java.sql.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.Properties;
import java.sql.DriverManager;
/**
* Created by Administrator on 2018/1/20 0020.
*/
public class Dbutils {
private static Properties properties;
private static String driverClassName;
private static String url;
private static String userName;
private static String password;
static {
try {
properties = new Properties();
properties.load(Dbutils.class.getClassLoader().getResourceAsStream("jdbc.properties"));
driverClassName = properties.getProperty("driverClassName");
url = properties.getProperty("url");
userName = properties.getProperty("userName");
password = properties.getProperty("password");
Class.forName(driverClassName);/*加载驱动*/
/* DriverManager.registerDriver(new com.mysql.jdbc.Driver());*/
}catch (Exception e){
throw new ExceptionInInitializerError("类加载驱动失败!");
}
}
/*连接驱动*/
public static Connection getConnection(){
Connection conn=null;
try{
conn = DriverManager.getConnection(url,userName,password);
}catch (SQLException e){
e.printStackTrace();;
}
return conn;
}
/*获取语句对象*/
public static java.sql.Statement getStatment(java.sql.Connection conn){
java.sql.Statement stat=null;
if(conn==null){
throw new IllegalArgumentException("连接对象为空无法获取语句对象");
}
try{
stat= conn.createStatement();
}catch (SQLException e){
e.printStackTrace();;
}
return stat;
}
/*获取预编译语句对象*/
public static java.sql.PreparedStatement getPreparedStatement(java.sql.Connection conn,String sql){
PreparedStatement preparedStat=null;
if(conn==null){
throw new IllegalArgumentException("连接对象为空无法获取预编译语句对象");
}
if(sql==null||"".equals(sql)){
throw new IllegalArgumentException("sql语句为空无法获取预编译语句对象");
}
try{
preparedStat= conn.prepareStatement(sql);
}catch (SQLException e){
e.printStackTrace();;
}
return preparedStat;
}
public static void closeConnection (java.sql.Connection conn){
try{
if(conn!=null){/*如果连接不为空*/
if(!conn.isClosed()){/*如果连接未关闭*/
conn.close();/*关闭连接*/
}
}
}catch (SQLException e){
e.printStackTrace();
}
}
/*关闭语句对象*/
public static void closeStatement (java.sql.Statement stat){
try{
if(stat!=null){/*如果连接不为空*/
if(!stat.isClosed()){/*如果连接未关闭*/
stat.close();/*关闭连接*/
}
}
}catch (SQLException e){
e.printStackTrace();
}
}
/*关闭结果集*/
public static void closeResult (ResultSet rs){
try{
if(rs!=null){/*如果连接不为空*/
if(!rs.isClosed()){/*如果连接未关闭*/
rs.close();/*关闭连接*/
}
}
}catch (SQLException e){
e.printStackTrace();
}
}
}
添加回答
2回答
相关分类