使用Java备份MySQL数据库

时间:2015-04-18 09:51:28

标签: java mysql backup

我需要使用Java备份MySQL数据库。即如果我运行类文件,它应该进行备份。即在特定位置创建转储文件。

2 个答案:

答案 0 :(得分:0)

这是我的样本解决方案。

 public static void main(String[] args) {

    Connection con = null;
    Statement st = null;
    ResultSet rs = null;

    String url = "jdbc:mysql://localhost/t";
    String user = "";
    String password = "";

    try {
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection(url, user, password);
        st = con.createStatement();
        rs = st.executeQuery("SELECT * FROM.........;");

        if (rs.next()) {//get first result
            System.out.println(rs.getString(1));//coloumn 1
            //TODO Write on your file
        }
    //TODO 
//**Process your file **/

    } catch (SQLException ex) {
        Logger lgr = Logger.getLogger(Version.class.getName());
        lgr.log(Level.SEVERE, ex.getMessage(), ex);

    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
            if (st != null) {
                st.close();
            }
            if (con != null) {
                con.close();
            }

        } catch (SQLException ex) {
            Logger lgr = Logger.getLogger(Version.class.getName());
            lgr.log(Level.WARNING, ex.getMessage(), ex);
        }
    }
}

链接:Some example are here.

要写入文件:How to write files in java

答案 1 :(得分:0)

下面的代码用户使用Java进行MySQL转储备份

public static void main(String[] args) {

        try {
            File dir = new File("/root/");
            Runtime runtime = Runtime.getRuntime();
            Process p = runtime.exec("mysqldump database_name >/path-for-backpfile/database.sql", null, dir);


            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

            String line = reader.readLine();


            while (line != null) {
                System.out.println(line);

                line = reader.readLine();
            }

        } catch (IOException e1) {
        }

    }