mysql 导出批量导出表数据 (程序)

Posted ..SunXin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mysql 导出批量导出表数据 (程序)相关的知识,希望对你有一定的参考价值。

private static String driverName = "com.mysql.jdbc.Driver";
public static void main(String[] args) {
Connection con = null ;
Statement stmt =null;
PreparedStatement pstmt = null ;
try {
Class.forName(driverName);
con = DriverManager.getConnection("jdbc:mysql://192.168.5.148/xxx", "root", "123456");
String sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ‘ifms‘ AND TABLE_TYPE =‘BASE TABLE‘ 
stmt = con.createStatement();
pstmt = con.prepareStatement(sql);
ResultSet res = stmt.executeQuery(sql);
while (res.next()) {
String tableName = res.getString(1);
/*stmt = con.createStatement();*/
if(tableName.contains("`")) continue;
File file = new File("C:\\Users\\hq\\Desktop\\sql\\mysql\\a_tables\\spf_data\\"+tableName+"_data.sql");
OutputStreamWriter osw = null;
try {
osw = new OutputStreamWriter(new FileOutputStream(file));
ResultSet rs = pstmt.executeQuery("desc `"+tableName+"`");
StringBuffer sb = new StringBuffer();
List<String> list = new ArrayList<String>();
while(rs.next()){
sb.append("`"+rs.getString(1)+"`,");
list.add("`"+rs.getString(2)+"`");
}
String str = sb.substring(0,sb.length()-1);
//str+=")";
System.out.println("select "+str+" from `"+tableName+"`");
ResultSet ress = pstmt.executeQuery("select "+str+" from `"+tableName+"`" );
while(ress.next()){
StringBuffer stb = new StringBuffer();
for(int i = 0 ;i<list.size();i++){
if(list.get(i).toLowerCase().contains("int")||list.get(i).toLowerCase().contains("decimal")||list.get(i).toLowerCase().contains("float")||list.get(i).toLowerCase().contains("double")){
stb.append(ress.getString(i+1)+",");
}else{
if(ress.getString(i+1)==null){
stb.append(ress.getString(i+1)+",");
}else{
stb.append("‘"+ress.getString(i+1)+"‘,");
}
}
}
String subs = stb.substring(0,stb.length()-1);
osw.write(" insert into `"+tableName+"`("+str+") values \n ("+subs+");\n");
}
System.out.println(tableName+"导出成功");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
osw.flush();
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.exit(1);
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(pstmt!=null){
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(con!=null){
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

}
}









以上是关于mysql 导出批量导出表数据 (程序)的主要内容,如果未能解决你的问题,请参考以下文章

mysql怎样导出表(表结构+数据)

navicat for MySQL怎么导出SQL脚本

navicat for MySQL怎么导出SQL脚本

navicat for MySQL怎么导出SQL脚本

navicat for MySQL怎么导出SQL脚本

navicat for MySQL怎么导出SQL脚本