今天试着写了一个java小程序,功能是调用windows下的mysqldump对某个数据库进行备份,代码如下,注意红色部分.
import java.sql.*;
import java.io.*;
public class MqldumpTest {
public static void main(String[] args) {
try {
String url = "jdbc:mysql://localhost/hxl";
String user = "root";
String pwd = "mysql";
// 加载驱动,这一句也可写为:Class.forName("com.mysql.jdbc.Driver");
Class.forName("com.mysql.jdbc.Driver").newInstance();
// 建立到MySQL的连接
Connection conn = DriverManager.getConnection(url, user, pwd);
// 执行SQL语句
Statement stmt = conn.createStatement();// 创建语句对象,用以执行sql语言
ResultSet rs = stmt
.executeQuery("select schema_name db_name from information_schema.SCHEMATA where schema_name=‘hxl‘ ");
// 处理结果集
while (rs.next()) {
String l_db_name = rs.getString("db_name");
System.out.println(l_db_name);
String command = "cmd /C mysqldump -h localhost -uroot -pmysql --default-character-set=gbk --single-transaction --databases hxl>E:\\mysqlbak\\hxl_bak_20140915.sql" ;
System.out.println(command);
Runtime r = Runtime.getRuntime();
Process p = r.exec(command);
}
rs.close();// 关闭数据库
conn.close();
} catch (Exception ex) {
System.out.println("Error : " + ex.toString());
}
}
}
如上程序执行成功了,但问题是生成的备份文件是0字节,这里mysqldump是自己调用mysql安装路径下的C:\Program Files\MySQL\MySQL Server 5.5\bin,网上查了说是路径有空格的问题,我试着将mysqldump.exe拷贝一份到c:\mysqldump\目录下,确保该路径没有空格,然后修改java代码里的代码,之间指定运行C:\mysqldump\mysqldump.exe,修改如下
String command = "cmd /C C:\\MOTOR OIL\\mysqldump -h localhost -uroot -pmysql --default-character-set=gbk --single-transaction --databases hxl>E:\\mysqlbak\\hxl_bak_20140915.sql" ;
再次运行后,正常生成了备份文件.
-- The End --