距離上班還有一段時間。現在總結一下如何使用Java語言實現MySQL數據庫導入:
首先新建名為test的數據庫;
其次執行下面Java代碼:
- import java.io.File;
- import java.io.IOException;
- /**
- * MySQL數據庫導入
- *
- * @author GaoHuanjie
- */
- public class MySQLDatabaseImport {
- /**
- * Java實現MySQL數據庫導入
- *
- * @author GaoHuanjie
- * @param hostIP MySQL數據庫所在服務器地址IP
- * @param userName 數據庫用戶名
- * @param password 進入數據庫所需要的密碼
- * @param importFilePath 數據庫文件路徑
- * @param sqlFileName 數據庫文件名
- * @param databaseName 要導入的數據庫名
- * @return 返回true表示導入成功,否則返回false。
- */
- public static boolean importDatabase(String hostIP, String userName, String password, String importFilePath, String sqlFileName, String databaseName) {
- File saveFile = new File(importFilePath);
- if (!saveFile.exists()) {// 如果目錄不存在
- saveFile.mkdirs();// 創建文件夾
- }
- if (!importFilePath.endsWith(File.separator)) {
- importFilePath = importFilePath + File.separator;
- }
- StringBuilder stringBuilder=new StringBuilder();
- stringBuilder.append("mysql").append(" -h").append(hostIP);
- stringBuilder.append(" -u").append(userName).append(" -p").append(password);
- stringBuilder.append(" ").append(databaseName);
- stringBuilder.append(" <").append(importFilePath).append(sqlFileName);
- try {
- Process process = Runtime.getRuntime().exec("cmd /c "+stringBuilder.toString());//必須要有“cmd /c ”
- if (process.waitFor() == 0) {// 0 表示線程正常終止。
- return true;
- }
- } catch (IOException e) {
- e.printStackTrace();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- return false;
- }
- public static void main(String[] args) throws InterruptedException {
- if (importDatabase("172.16.0.127", "root", "123456", "D:\\backupDatabase", "2014-10-14.sql", "GHJ")) {
- System.out.println("數據庫導入成功!!!");
- } else {
- System.out.println("數據庫導入失敗!!!");
- }
- }
- }