通过 Java 以编程方式导入 (mysql) 数据库转储

2022-09-03 01:24:03

如何通过java程序以编程方式导入mysql数据库转储文件(包含插入和创建表语句)。我需要将其作为单元测试的设置阶段。

不幸的是,这不起作用:

Connection conn = dbConnectionSource.getConnection();
Statement stmt = conn.createStatement();
stmt.execute(FileUtils.readFileToString(new File("./some-sql-file")));
conn.close();

谢谢, -A

PS - 在Rails中,我使用夹具来填充测试数据库。我让 Rails Rails 通过设置要测试的环境来创建基础表,这在 Java 中是类似的。


答案 1

您可以从java启动一个新进程,并在运行导入的任何地方访问mysql可执行文件并执行此命令。像这样:

Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("mysql -p -h ServerName DbName < dump.sql");

答案 2

备份:

/******************************************************/
//Database Properties
/******************************************************/
String dbName = “dbName”;
String dbUser = “dbUser”;
String dbPass = “dbPass”;

/***********************************************************/
// Execute Shell Command
/***********************************************************/
String executeCmd = “”;
executeCmd = “mysqldump -u “+dbUser+” -p”+dbPass+” “+dbName+” -r backup.sql”;
}
Process runtimeProcess =Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if(processComplete == 0){

out.println(“Backup taken successfully”);

} else {

out.println(“Could not take mysql backup”);

}

恢复:

/******************************************************/
//Database Properties
/******************************************************/
String dbName = “dbName”;
String dbUser = “dbUser”;
String dbPass = “dbPass”;

/***********************************************************/
// Execute Shell Command
/***********************************************************/
String executeCmd = “”;

executeCmd = new String[]{“/bin/sh”, “-c”, “mysql -u” + dbUser+ ” -p”+dbPass+” ” + dbName+ ” < backup.sql” };

}
Process runtimeProcess =Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if(processComplete == 0){

out.println(“success”);

} else {

out.println(“restore failure”);

}

推荐