📄 databaseutil.java
字号:
package cn.edu.dlnu.frame.utils;
import java.util.*;
import java.sql.*;
public class DataBaseUtil {
private static String url, driver, user, password;
private Connection connection = null;
static {
ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
try {
url = bundle.getString("jdbc.url");
driver = bundle.getString("jdbc.driverClassName");
user = bundle.getString("jdbc.username");
password = bundle.getString("jdbc.password");
} catch (Exception e) {
e.printStackTrace();
}
}
public DataBaseUtil() {
try {
Class.forName(driver);
connection = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
protected void finalize() throws Throwable {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
super.finalize();
}
public void beginTransaction(){
try{
connection.setAutoCommit(false);
}catch(SQLException e){
e.printStackTrace();
}
}
public void commit(){
try{
connection.commit();
connection.setAutoCommit(true);
}catch(SQLException e){
e.printStackTrace();
}
}
public void rollback(){
try{
connection.rollback();
connection.setAutoCommit(true);
}catch(SQLException e){
e.printStackTrace();
}
}
public List<Map<String, Object>> queryForList(String sql, Object[] params) {
PreparedStatement stmt = null;
ResultSet rs = null;
List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
;
try {
stmt = connection.prepareStatement(sql);
if (params != null) {
for (int i = 0; i < params.length; i++) {
stmt.setObject(i + 1, params[i]);
}
}
rs = stmt.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
while (rs.next()) {
Map<String, Object> row = new HashMap<String, Object>();
for (int i = 0; i < count; i++) {
row.put(rsmd.getColumnName(i + 1), rs.getObject(i + 1));
}
result.add(row);
}
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
public Map<?, ?> queryForMap(String sql, Object[] params) throws Exception {
List<?> result = queryForList(sql, params);
if (result.size() == 1) {
return (Map<?, ?>) result.get(0);
} else {
throw new Exception("except 1 row actually return " + result.size() + "rows");
}
}
public boolean executeUpdate(String sql, Object[] params) {
PreparedStatement stmt = null;
int result = -1;
try {
stmt = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
stmt.setObject(i + 1, params[i]);
System.out.print(params[i]);
}
result = stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
if (result > 0) {
return true;
} else {
return false;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -