package com.awspaas.user.apps.scienceriskrecord.controller.riskTaking;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.*;
public class MySQLTableExporter {
private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_URL = "jdbc:mysql://localhost:3306/as?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false";
private static final String USER = "root";
private static final String PASSWORD = "as@&d1";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
BufferedWriter writerTableSQL = null;
BufferedWriter writer = null;
System.out.println("开始导出!");
try {
// 注册 JDBC 驱动
Class.forName(JDBC_DRIVER);
// 打开连接
conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
// 要导出的表名
String tableNames = "bwhitelist11";
// String[] tableNames = {"bo_eu_whitelist11"};
// 创建文件写入器
writerTableSQL = new BufferedWriter(new FileWriter("D:\\tableSQL.sql"));
writer = new BufferedWriter(new FileWriter("D:\\SSSSt.sql"));
// 导出建表语句
String createTableSQL = getCreateTableSQL(conn, tableNames);
writerTableSQL.write(createTableSQL);
writerTableSQL.newLine();
// 导出插入数据语句
String insertDataSQL = getInsertDataSQL(conn, tableNames);
writer.write(insertDataSQL);
writer.newLine();
System.out.println("导出成功!");
} catch (ClassNotFoundException | SQLException | IOException e) {
e.printStackTrace();
} finally {
// 关闭资源
try {
if (writerTableSQL != null)
writerTableSQL.close();
if (writer != null)
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (stmt != null)
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// 获取建表语句
private static String getCreateTableSQL(Connection conn, String tableName) throws SQLException {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SHOW CREATE TABLE " + tableName);
rs.next();
String createTableSQL = rs.getString(2);
rs.close();
stmt.close();
return createTableSQL;
}
// 获取插入数据语句
private static String getInsertDataSQL(Connection conn, String tableName) throws SQLException {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName);
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
StringBuilder insertDataSQL = new StringBuilder();
StringBuilder insert_into_ = null;
while (rs.next()) {
StringBuilder values = new StringBuilder();
for (int i = 1; i <= columnCount; i++) {
Object value = rs.getObject(i);
if (value != null) {
if (i > 1) {
values.append(", ");
}
values.append("'").append(value).append("'");
}
}
insert_into_ = insertDataSQL.append("INSERT INTO ").append(tableName).append(" VALUES (").append(values).append(");");
insertDataSQL.append("\n");
}
return insert_into_.toString();
}
}
java 实现导出mysql某个表的建表语句并且导出插入数据的sql文件脚本
于 2024-01-16 15:11:54 首次发布