public int writeDB(String sql) {
return writeDB(sql, null);
}
//写数据库方法
public static int writeDB(String sql, Object[] params) {
Connection con = null;
PreparedStatement ps = null;
ResultSet re = null;
int row = 0;
try {
con = MySql.getCon();
ps = (PreparedStatement) con.prepareStatement(sql);
if (params != null) {
for (int i = 0; i < params.length; i++) {
ps.setObject(i + 1, params);
}
}
row = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
MySql.free(re, ps, con);
}
return row;
}
//读数据库方法
public static List<Map<String, Object>> readDB(String sql, Object[] params) {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
// map<>里,string 是键,就是列名,object是值,是集合,一个map得到一行记录
try {
con = Tool.getCon();
ps = con.prepareStatement(sql);
// sql语句参数化
if (params != null) {
for (int i = 0; i < params.length; i++) {
ps.setObject(i + 1, params);
}
}
rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();// 一共获得几列
String[] columName = new String[count];
for (int i = 0; i < count; i++) {
columName = rsmd.getColumnName(i + 1);// 获得列名
}
while (rs.next()) {
HashMap<String, Object> map = new HashMap<String, Object>();
for (int i = 0; i < count; i++) {
map.put(columName, rs.getObject(i + 1));