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.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* <p>类描述: oracle jdbc 示例 </p>
* <p>创建人:whg </p>
* <p>创建时间:2021年7月8日 下午7:22:16 </p>
*/
public class OracleUtil {
public static final String DRIVER = "oracle.jdbc.driver.OracleDriver";
private static Connection conn = null;
/**
* 通过静态代码块 注册数据库驱动
*/
static {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 获得Connection
*
* @return
*/
public Connection getConnection(String url,String username,String password) {
try {
if(null == conn || conn.isClosed()){
conn = DriverManager.getConnection(url, username, password);
}
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
/**
* 获得Statement
*
* @return
*/
public Statement getStatement() {
Statement st = null;
try {
if(null != conn && !conn.isClosed()){
st = conn.createStatement();
}
} catch (SQLException e) {
e.printStackTrace();
}
return st;
}
/**
* 关闭ResultSet
*
* @param rs
*/
public void closeResultSet(ResultSet rs) {
if (null != rs) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 关闭Statement
*
* @param st
*/
public void closeStatement(Statement st) {
if (null != st) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 关闭Connection
*
* @param conn
*/
public void closeConnection(Connection conn) {
if (null != conn) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 关闭全部
*
* @param rs
* @param sta
* @param conn
*/
public void closeAll(ResultSet rs, Statement sta, Connection conn) {
closeResultSet(rs);
closeStatement(sta);
closeConnection(conn);
}
/**
* 查询
*
* @return
*/
public List<Map<String, Object>> query(String sql, String url, String username, String password) {
List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
PreparedStatement pst = null;
ResultSet rs = null;
Connection conn = getConnection(url,username,password);
try {
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
//获取结果集的元数据
ResultSetMetaData md = rs.getMetaData();
//获取结果集元数据中的列数
int columnCount = md.getColumnCount();
while (rs.next()) {
Map<String, Object> map = new HashMap<>();
for (int i = 0; i < columnCount; i++) {
Object colDate = rs.getObject(i + 1);
String colName = md.getColumnLabel(i + 1);
//放入数组
map.put(colName,colDate);
}
//放入集合
resultList.add(map);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeAll(rs,pst,conn);
}
return resultList;
}
}