pom.xml 添加ant
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.10.9</version>
<exclusions>
<exclusion>
<artifactId>tools</artifactId>
<groupId>com.sun</groupId>
</exclusion>
</exclusions>
</dependency>
import lombok.extern.slf4j.Slf4j;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.SQLExec;
import org.springframework.util.ResourceUtils;
import java.io.File;
import java.util.Properties;
@Slf4j
public class ScriptSql {
private static final String SCRIPT_SQL = "classpath:test.sql";
public static void exeSQLSript(Properties prop) throws Exception {
String[] sqlName = {SCRIPT_SQL};
for (int i = 0; i < sqlName.length; i++) {
SQLExec sqlExec = new SQLExec();
String mysqlDriver = prop.getProperty("driver","com.mysql.cj.jdbc.Driver");
String url = prop.getProperty("url");
String username = prop.getProperty("username","root");
String password = prop.getProperty("password","root");
sqlExec.setDriver(mysqlDriver);
sqlExec.setUrl(url);
sqlExec.setUserid(username);
sqlExec.setPassword(password);
sqlExec.setEncoding("UTF8");
File file = ResourceUtils.getFile(SCRIPT_SQL);
sqlExec.setSrc(file);
sqlExec.setPrint(true);
sqlExec.setProject(new Project());
sqlExec.setOutputEncoding("UTF8");
sqlExec.setAutocommit(true);
sqlExec.execute();
log.info("sqlExec execute success!");
}
}
public static void main(String[] args) {
Properties prop = new Properties();
prop.setProperty("url", "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=Asia/Shanghai");
prop.setProperty("username", "root");
prop.setProperty("password", "root");
try {
ScriptSql.exeSQLSript(prop);
} catch (Exception e) {
e.printStackTrace();
}
}
}
注意:这里的test 数据源是已经存在的,否则会报异常Unknown database 'test' 执行之前 执行之后 自动创建了相关的表 可以应用到系统升级时自动更新表结构或创建新表,避免人工干预
|