Java实现MySQL数据库导入

使用shell命令的方式

package com.ttsx.demo.test;

import java.io.File;
import java.io.IOException;

/**
 * @author sunjilong
 * @date 2021/8/30 10:33
 * @info
 */
public class SqlTest {

    /**
     * Java实现MySQL数据库导入
     *
     * @author sunjilong
     * @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());//windows必须要有“cmd /c ”,linux去掉 “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("127.0.0.1", "root", "root", "D:\\", "test.sql", "test")) {
            System.out.println("数据库导入成功!!!");
        } else {
            System.out.println("数据库导入失败!!!");
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值