日期:2014-05-16 浏览次数:20985 次
? 由于要清空数据库数据 ,手动非常麻烦。网上找了一下,有一个Oracle的,参照它,在其上修改一下用于Mysql,把代码奉献如下:
?相关连接:
?
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.UnavailableException; import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException; /** * @author Bicashy,fencer911(for Mysql Version) */ public class TableOperate { static Statement stmt = null; static Connection conn = null; static Map map = new HashMap(); //用来保存已经删除了的表的集合 static Map filterMap = new HashMap(); //用来保存需要过滤的表的集合 static String schema ; /** * 获得数据库链接 * @return */ private static Connection getConnection(){ try { Class.forName( "com.mysql.jdbc.Driver").newInstance(); //String url= "jdbc:oracle:thin:@10.45.10.177:1521:highway"; String url= "jdbc:mysql://localhost:3306/laidong8v5?useUnicode=true&characterEncoding=utf-8"; String user= "java"; String password= "java"; schema = user; conn = DriverManager.getConnection(url,user,password); return conn; } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /** * 获得该用户的所有表,并删除表(除了要过滤的表) */ private static void findDeleteTableSQL(){ if(conn!=null){ try { stmt=conn.createStatement(); String sql = "show TABLES"; //找到该链接用户的所有表 ResultSet rs=stmt.executeQuery(sql); while(rs.next()){ String tabName = rs.getString(1); //getString("table_name"); //如果map中包含了表名,说明已经删除过了 //如果filterMap中包含了表名,则不删除 if(!map.containsKey(tabName)&&!filterMap.containsKey(tabName)){ printDeleteTableSQL(tabName); } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * * 删除表,并将删除表的语句输出到控制台(记录后方便在数据库客户端执行) * @param l * @param tableName * @return */ private static void printDeleteTableSQL(String tableName){ String sql = "DELETE FROM "+tableName.toUpperCase(); try { stmt=conn.createStatement(); System.out.println(sql+";"); stmt.execute(sql); stmt.close(); //将删除语句输出到控制台 map.put(tableName,null); } catch (MySQLIntegrityConstraintViolationException e) { // TODO Auto-generated catch block String error = e.toString(); System.out.println(error); int p1=error.indexOf("("); int p2=error.indexOf("FOREIGN KEY"); error=error.substring(p1, p2); int p3=error.indexOf("CONSTRAINT"); error=error.substring(p3); error=error.replaceAll("CONSTRAINT", "").replaceAll(" ", "").replaceAll("`", "");