JDBC通用连接、增删改查类
package com.xxx.yyy.dao;
import java.sql.*;
public class DBUtil {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String URL = "jdbc:mysql://localhost:3306/his";
static final String USERNAME = "root";
static final String PASSWORD = "root";
public static Connection connection = null;
public static PreparedStatement pstmt = null;
public static ResultSet rs = null;
public static Connection getConnection() throws SQLException, ClassNotFoundException {
Class.forName(JDBC_DRIVER);
return DriverManager.getConnection(URL,USERNAME,PASSWORD);
}
public static Connection getOneConnection() throws SQLException, ClassNotFoundException {
if (DBUtil.connection == null) {
return getConnection();
} else {
return DBUtil.connection;
}
}
public static PreparedStatement createPreParedStatement(String sql,Object[] params) throws SQLException, ClassNotFoundException {
connection = getOneConnection();
pstmt = connection.prepareStatement(sql);
if (params != null) {
for (int i = 0; i < params.length; i++) {
pstmt.setObject((i+1),params[i]);
}
}
return pstmt;
}
public static boolean executeUpdate(String sql,Object[] params) {
try {
pstmt = createPreParedStatement(sql, params);
int count = pstmt.executeUpdate();
if (count > 0) {
return true;
} else {
return false;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
return false;
} catch (SQLException e) {
e.printStackTrace();
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
closeAll(connection, pstmt, rs);
}
}
public static ResultSet executeQuery(String sql,Object[] params) {
try {
pstmt = createPreParedStatement( sql,params);
rs = pstmt.executeQuery();
return rs;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
} catch (SQLException e) {
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void closeAll(Connection connection,Statement pstmt,ResultSet rs) {
try {
if (pstmt!=null) pstmt.close();
if (rs!=null) rs.close();
if (connection!=null) connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}