Java實現MySQL數據庫導入


  距離上班還有一段時間。現在總結一下如何使用Java語言實現MySQL數據庫導入:

        首先新建名為test的數據庫;

        其次執行下面Java代碼:

 

[java]  view plain  copy
 
  1. import java.io.File;  
  2. import java.io.IOException;  
  3.   
  4. /** 
  5.  * MySQL數據庫導入 
  6.  *  
  7.  * @author GaoHuanjie 
  8.  */  
  9. public class MySQLDatabaseImport {  
  10.   
  11.     /** 
  12.      * Java實現MySQL數據庫導入 
  13.      *  
  14.      * @author GaoHuanjie 
  15.      * @param hostIP MySQL數據庫所在服務器地址IP 
  16.      * @param userName 數據庫用戶名 
  17.      * @param password 進入數據庫所需要的密碼 
  18.      * @param importFilePath 數據庫文件路徑 
  19.      * @param sqlFileName 數據庫文件名 
  20.      * @param databaseName 要導入的數據庫名 
  21.      * @return 返回true表示導入成功,否則返回false。 
  22.      */  
  23.     public static boolean importDatabase(String hostIP, String userName, String password, String importFilePath, String sqlFileName, String databaseName) {  
  24.         File saveFile = new File(importFilePath);  
  25.         if (!saveFile.exists()) {// 如果目錄不存在  
  26.             saveFile.mkdirs();// 創建文件夾  
  27.         }  
  28.         if (!importFilePath.endsWith(File.separator)) {  
  29.             importFilePath = importFilePath + File.separator;  
  30.         }         
  31.   
  32.         StringBuilder stringBuilder=new StringBuilder();  
  33.         stringBuilder.append("mysql").append(" -h").append(hostIP);  
  34.         stringBuilder.append(" -u").append(userName).append(" -p").append(password);  
  35.         stringBuilder.append(" ").append(databaseName);  
  36.         stringBuilder.append(" <").append(importFilePath).append(sqlFileName);  
  37.         try {  
  38.             Process process = Runtime.getRuntime().exec("cmd /c "+stringBuilder.toString());//必須要有“cmd /c ”  
  39.             if (process.waitFor() == 0) {// 0 表示線程正常終止。  
  40.                 return true;  
  41.             }  
  42.         } catch (IOException e) {  
  43.             e.printStackTrace();  
  44.         } catch (InterruptedException e) {  
  45.             e.printStackTrace();  
  46.         }  
  47.         return false;  
  48.     }  
  49.   
  50.     public static void main(String[] args) throws InterruptedException {  
  51.         if (importDatabase("172.16.0.127", "root", "123456", "D:\\backupDatabase", "2014-10-14.sql", "GHJ")) {  
  52.             System.out.println("數據庫導入成功!!!");  
  53.         } else {  
  54.             System.out.println("數據庫導入失敗!!!");  
  55.         }  
  56.     }  
  57. }  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM