在工作中我们需要实现java程序执行sql脚本的场景,spring提供了一个很方便的工具类ScriptUtils配合dataSource(import javax.sql.DataSource;)给大家使用。具体代码如下:
@Slf4j
@Service("dataService")
public class DataServiceImpl extends ServiceImpl implements DataService {
@Autowired
private DataMapper dataMapper;
@Autowired
private DataSource dataSource;
@Override
public BaseResult data() {
DataEntity entity = dataMapper.selectById(1);
if (ObjectUtil.isNull(entity)) {
return BaseResult.succeed(1);
} else {
if (entity.getDc() == 1) {
return BaseResult.succeed(1);
}
}
return BaseResult.succeed(0);
}
@Override
public void dcOne() {
try {
PathResource resource = new PathResource("D:\data\movedata.sql");
ScriptUtils.executeSqlScript(dataSource.getConnection(), resource);
} catch (Exception e) {
log.error("========执行数据迁移时出错", e);
if (!check(1)) {
DataEntity entity = new DataEntity();
entity.setDc(0);
dataMapper.insert(entity);
}
}
if (!check(1)) {
DataEntity entity = new DataEntity();
entity.setDc(1);
dataMapper.insert(entity);
}
}
public boolean check(Integer id) {
DataEntity entity = dataMapper.selectById(id);
if (ObjectUtil.isNull(entity)) {
return false;
} else {
return true;
}
}
}
`



