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/your_database";
private static final String USER = "your_username";
private static final String PASSWORD = "your_password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
BufferedWriter writer = null;
try {
// 注册 JDBC 驱动
Class.forName(JDBC_DRIVER);
// 打开连接
conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
// 要导出的表名
String[] tableNames = {"table1", "table2", "table3"};
// 创建文件写入器
writer = new BufferedWriter(new FileWriter("export.sql"));
// 遍历每个表进行导出
for (String tableName : tableNames) {
// 导出建表语句
String createTableSQL = getCreateTableSQL(conn, tableName);
writer.write(createTableSQL);
writer.newLine();
// 导出插入数据语句
String insertDataSQL = getInsertDataSQL(conn, tableName);
writer.write(insertDataSQL);
writer.newLine();
}
System.out.println("导出成功!");
} catch (ClassNotFoundException | SQLException | IOException e) {
e.printStackTrace();
} finally {
// 关闭资源
try {
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();
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("'");
}
}
insertDataSQL.append("INSERT INTO ").append(tableName).append(" VALUES (").append(values).append(");");
insertDataSQL
java怎么实现导出mysql某些表的建表和插入数据的sql文件?
最新推荐文章于 2024-08-14 04:22:05 发布