[Java] 数据库连接管理类

时间:2023-03-10 02:42:50
[Java] 数据库连接管理类
package com.wdcloud.monitoring.common;
/**
* @Description: TODO
* @date: 2015��11��19�� ����10:23:16
* @version: 1.0
* @update [����YYYY-MM-DD] [���������][�������]
*/ import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import com.mysql.jdbc.Statement; /**
* 连接数据库的工具类,被定义成不可继承且是私有访问
*/
public final class DBUtils {
private static String url = "jdbc:mysql://localhost:3306/test";
private static String user = "root";
private static String psw = "root"; private static Connection conn;
private static Statement statement; static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
} private DBUtils() { } /**
* 获取数据库的连接
* @return conn
*/
public static Connection getConnection() {
if(null == conn) {
try {
conn = DriverManager.getConnection(url, user, psw);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
return conn;
} public static Statement getStatement(){
if(null == statement){
try{
statement = (Statement) DBUtils.getConnection().createStatement();
}catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
return statement;
} /**
* 释放资源
* @param conn
* @param pstmt
* @param rs
*/
public static void closeResources(Connection conn,PreparedStatement pstmt,ResultSet rs) {
if(null != rs) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
if(null != pstmt) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
if(null != conn) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
}
}
}
} /**
*
* @Description: TODO 将ResultSet转成list
* @date: 2015年11月19日 下午2:08:25
* @version: 1.0
* @param rs
* @return
* @throws java.sql.SQLException
* @List
* @update [日期YYYY-MM-DD] [更改人姓名][变更描述]
*/
public static List resultSetToList(ResultSet rs) throws java.sql.SQLException {
if (rs == null)
return Collections.EMPTY_LIST;
ResultSetMetaData md = rs.getMetaData(); //得到结果集(rs)的结构信息,比如字段数、字段名等
int columnCount = md.getColumnCount(); //返回此 ResultSet 对象中的列数
List list = new ArrayList();
Map rowData = new HashMap();
while (rs.next()) {
rowData = new HashMap(columnCount);
for (int i = 1; i <= columnCount; i++) {
rowData.put(md.getColumnName(i), rs.getObject(i));
}
list.add(rowData);
}
return list;
} }