前言
在程序执行过程中,难免会遇到一些建表等数据库操作
如果只有一个操作,可以执行在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();
}
数据库必须提前创建好