package util;
/**
* 连接数据库
*/
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBUtil {
/**
* 获取连接
*
* @return Connection
* @throws Exception 异常
*/
public static Connection getCon() throws Exception {
//数据库驱动名字
String jdbcName = "com.mysql.jdbc.Driver";
Class.forName(jdbcName);
//数据库协议地址
String dbUrl = "jdbc:mysql://ip:3306/databaseName?useUnicode=true&characterEncoding=UTF-8";
//数据库用户名
String dbUser = "username";
//数据库密码
String dbPassword = "password";
Connection conn = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
return conn;
}
/**
* 关闭连接
*
* @param stmt Statement
* @param conn Connection
* @throws Exception 异常
*/
public static void close(Statement stmt, Connection conn) throws Exception {
if (stmt != null) {
stmt.close();
if (conn != null) {
conn.close();
}
}
}
/**
* 关闭连接
*
* @param cstmt CallableStatement
* @param conn Connection
* @throws Exception 异常
*/
public static void close(CallableStatement cstmt, Connection conn) throws Exception {
if (cstmt != null) {
cstmt.close();
if (conn != null) {
conn.close();
}
}
}
/**
* 关闭连接
*
* @param pstmt PreparedStatement
* @param conn Connection
* @throws SQLException SQL异常
*/
public static void close(PreparedStatement pstmt, Connection conn) throws SQLException {
if (pstmt != null) {
pstmt.close();
if (conn != null) {
conn.close();
}
}
}
/**
* 重载关闭方法
*
* @param pstmt PreparedStatement
* @param conn Connection
* @throws Exception 异常
*/
public static void close(ResultSet rs, PreparedStatement pstmt, Connection conn) {
if (rs != null) {
try {
rs.close();
if (pstmt != null) {
pstmt.close();
if (conn != null) {
conn.close();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}