如何使用java备份mssql数据库?

时间:2013-11-21 12:03:21

标签: java

我目前正在使用Mssql2000。如何使用java应用程序备份此数据库?有可能吗?

2 个答案:

答案 0 :(得分:1)

只需使用jdbc运行备份数据库脚本......

BACKUP DATABASE 'databaseOfNames' TO DISK = 'c:\myFile' 

所以你做了类似......

的事情
 try (
         // Step 1: Allocate a database "Connection" object
         Connection conn = DriverManager.getConnection(
               "jdbc:mysql://localhost:8888/ebookshop", "myuser", "password"); // MySQL

         // Step 2: Allocate a "Statement" object in the Connection
         Statement stmt = conn.createStatement();
      ) {
         String strSelect = "BACKUP DATABASE 'databaseOfNames' TO DISK = 'c:\myFile' ";
         ResultSet rset = stmt.execute(strSelect);
      }

应该注意,这使用新的JDK7 try-with-resources代码,因此它会自动关闭资源。

答案 1 :(得分:0)

仅在您在本地访问数据库时才使用以下代码。

 public boolean backupDB(String dbName, String path) {
    String executeCmd = "BACKUP DATABASE '"+ dbName +"' TO DISK = '"+ path +"' ";
    Process runtimeProcess;
    try {

        runtimeProcess = Runtime.getRuntime().exec(executeCmd);
        int processComplete = runtimeProcess.waitFor();

        if (processComplete == 0) {
            System.out.println("Backup created successfully");
            return true;
        } else {
            System.out.println("Could not create the backup");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return false;
}

有关SQL备份的更多信息,请参阅此URL