对创建连接、查询、增删改 的简单封装,在数据库事务案例中,该类不是关键,只是为了方便验证例子,做的简单封装
package test;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Db {
public static Connection connect(String driver,String url,String username,String password) throws ClassNotFoundException, SQLException {
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, username, password);
return connection;
}
public static int update(Connection connection,String sql) throws SQLException {
PreparedStatement ps = null;
try {
ps= connection.prepareStatement(sql);
int i = ps.executeUpdate();
return i;
}finally {
if(ps!=null) {
ps.close();
}
}
}
public static List<Map> query(Connection connection, String sql) throws SQLException{
PreparedStatement pstm = null;
ResultSet rs = null;
List<Map> retList = new ArrayList();
try {
pstm = connection.prepareStatement(sql);
rs = pstm.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
//查询的列数
int count=rsmd.getColumnCount();
while(rs.next()){
Map record=new HashMap();
for(int i=0 ; i<count ; i++ ){
record.put(rsmd.getColumnLabel(i+1), rs.getObject(i+1));
}
//将数组放入到List中
retList.add(record);
}
}finally {
//查询后要释放资源
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
}
}
if(pstm!=null) {
try {
pstm.close();
} catch (SQLException e) {
}
}
}
return retList;
}
}