Java语言执行SQL脚本文件

前言

在程序执行过程中,难免会遇到一些建表等数据库操作
如果只有一个操作,可以执行在XML里编写。但是有多个时,就需要像Navicat这种开发工具直接执行SQL文件,在Java里同样也可以。

主要依赖

MySQL驱动必不可少
执行SQL文件需要用到Mybatis,MP也是可以的

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.1</version>
</dependency>

具体操作

1、获取驱动

这里MySQL版本为8.0

public Connection getManagerConnection(String database, String username, String password) throws Exception {
        String url = "jdbc:p6spy:mysql://localhost:3306/"+database+"?useSSL=false&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&rewriteBatchedStatements=true&cachePrepStmts=true&useServerPrepStmts=true&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT%2B8";
        Class.forName("com.mysql.cj.jdbc.Driver");
        return DriverManager.getConnection(url,username,password);
    }

2、获取文件

获取File只是为了校验文件,可以不校验,执行调用第五步执行

public String test(){
	String database = "xxx";
	String username = "root";
	String password = "1234";
	
	// 获取classpath下的sql文件
	ClassPathResource classPathResource = new ClassPathResource("sql/xxx.sql");
	InputStream is = classPathResource.getInputStream();
	InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
	// 直接编写第五步执行就好
	// xxx
	
	// 获取绝对路径下的sql文件
	String path = "D:\xxx.sql";
	// 调用获取结果
	dataRecovery(path,database,username,password);
}

3、校验文件并执行返回结果

public String dataRecovery(String filePath, String database, String username, String password) {
    try {
        File file = new File(filePath); // 转换成File对象
        if (!file.exists()) {
            return "该文件不存在"; // 路径错误
        }
        if (file.isFile()){
        	// 该路径表示一个文件
            String fileName = file.getName();
            String fileNameLast = fileName.substring(fileName.indexOf("."));
            if (".sql".equals(fileNameLast)){
            	// 如果是sql文件执行
                initTable(database,username,password,file);
            } else{
                return "文件格式错误";
            }
        }
        if (file.isDirectory()){
        	// 该路径表示一个文件夹
            File f = getFile(file); // 公共方法,下面提供
            if (null == f){
                return "文件格式错误";
            }
            // 如果是sql文件执行
            initTable(database,username,password,f);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "成功";
}

4、文件夹中获取sql文件getFile()

如果想获取多层的,递归就好,我就搞一层。

public File getFile(File file){
    File[] files = file.listFiles();
    for (File f : files) {
        if (f.isFile()) {
            String fileName = f.getName();
            String fileNameLast = fileName.substring(fileName.indexOf("."));
            if (".sql".equals(fileNameLast)){
                return f;
            }
        }
    }
    return null;
}

5、执行SQL文件

public void initTable(String database,String username, String password, File file) throws Exception {
    Connection conn = getManagerConnection(database, username, password);
    FileReader reader = new FileReader(file);
    ScriptRunner scriptRunner = new ScriptRunner(conn);
    // 设置编码,防止中文乱码
    Resources.setCharset(Charset.forName("UTF-8"));
    // 必须为true,不然容易报错
    scriptRunner.setSendFullScript(true);
    // 执行
    scriptRunner.runScript(reader);
    scriptRunner.closeConnection();
    reader.close();
}

数据库必须提前创建好

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是Smoky呢

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值