显示某个数据库下的所有表
public List<String> showTables() {
List<String> tables = new ArrayList<String>();
try {
PreparedStatement stmt = null;
Connection conn = null;
conn = ConnectionTools.getConn();
conn.setAutoCommit(false);
String sql = "show tables";
stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
String table = rs.getString(1);
tables.add(table);
}
conn.commit();
conn.close();
stmt.close();
} catch (Exception e) {
e.printStackTrace();
}
return tables;
}
给某个表添加一个列:
public void crateCloum() { List<String> tables = showTables(); for (String string : tables) { try { PreparedStatement stmt = null; Connection conn = null; conn = ConnectionTools.getConn(); conn.setAutoCommit(false); String sql = "alter table " + string + " add mobileLinks varchar(200) null"; stmt = conn.prepareStatement(sql); stmt.executeUpdate(); conn.commit(); conn.close(); stmt.close(); } catch (Exception e) { e.printStackTrace(); } } }
对list类型的数据插入到数据库中,批处理
public void addCanshu(List<Canshu> list) { // System.out.println(list.size()); Connection conn = ConnectionTools.getConn(); try { conn.setAutoCommit(false); String sql = "insert canshu(urlId,firstClass,canshukey,canshuvalue) values(?,?,?,?)"; PreparedStatement ps = conn.prepareStatement(sql); for (Canshu product : list) { ps.setString(1, product.getUrlID()); ps.setString(2, product.getFirstClass()); ps.setString(3, product.getKey()); ps.setString(4, product.getValue()); ps.addBatch(); } ps.executeBatch(); conn.commit(); } catch (SQLException e) { try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } e.printStackTrace(); } finally { try { ConnectionTools.close(); } catch (Exception e) { e.printStackTrace(); } } }
更新数据库例子
public void updateCanmore() { List<Canshu> tables = getCanshuInSql(); for (Canshu c : tables) { try { PreparedStatement stmt = null; Connection conn = null; conn = ConnectionTools.getConn(); conn.setAutoCommit(false); String sql = "update canmore set " + c.getKey() + "= '" + c.getValue().trim() + "' where urlId=" + c.getUrlID(); System.out.println(sql); stmt = conn.prepareStatement(sql); stmt.execute(); conn.commit(); conn.close(); stmt.close(); } catch (Exception e) { e.printStackTrace(); } } }
