原始jdbc操作连接数据库的工具类
public class JdbcUtil {
/**
* 定义数据库的链接
*/
private Connection conn;
/**
* 定义sql语句的执行对象
*/
private PreparedStatement pstmt;
/**
* 定义查询返回的结果集合
*/
private ResultSet rs;
/**
* jdbc构造器
* @param driver
* @param url
* @param username
* @param password
*/
public JdbcUtil(String driver, String url, String username, String password) {
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
Jlog.info("数据库连接成功");
} catch (Exception e) {
Jlog.error("error:", e);
}
}
/**
*功能描述 更新数据
* @param sql
* @param params
* @return boolean
*/
public boolean updateByParams(String sql, List<Object> params) throws SQLException {
// 影响行数
int result = -1;
pstmt = conn.prepareStatement(sql);
int index = 1;
// 填充sql语句中的占位符
if (null != params && !params.isEmpty()) {
for (int i = 0; i < params.size(); i ++) {
pstmt.setObject(index ++, params.get(i));
}
}
result = pstmt.executeUpdate();
return result > 0 ? true : false;
}
/**
*功能描述 查询多条记录
* @param sql
* @param params
* @return java.util.List<java.util.Map>
* @date 2020/6/9
*/
public List<Map<String,Object>> selectByParams(String sql, List<Object> params) throws SQLException {
List<Map<String,Object>> list = new ArrayList<Map<String,Object>> ();
int index = 1;
pstmt = conn.prepareStatement(sql);
if (null != params && !params.isEmpty()) {
for (int i = 0; i < params.size(); i ++) {
pstmt.setObject(index++, params.get(i));
}
}
rs = pstmt.executeQuery();
ResultSetMetaData metaData = rs.getMetaData();
int colsLen = metaData.getColumnCount();
while (rs.next()) {
Map<String,Object> map = new HashMap<String,Object>(colsLen);
for (int i = 0; i < colsLen; i ++) {
String columnName = metaData.getColumnName(i + 1);
Object columnValue = rs.getObject(columnName);
if (null == columnValue) {
columnValue = "";
}
map.put(columnName, columnValue);
}
list.add(map);
}
return list;
}
/**
*功能描述 释放连接
* @return## 标题
* @date 2020/6/9
*/
public void release() {
try {
if(null != rs){
try {
rs.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if(null != pstmt){
try {
pstmt.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if(null!=conn){
try {
conn.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
} catch (SQLException e) {
Jlog.error("error:", e);
}
Jlog.info("释放数据库连接");
}
}