在工作中我们需要实现java程序执行sql脚本的场景,spring提供了一个很方便的工具类ScriptUtils配合dataSource(import javax.sql.DataSource;)给大家使用。具体代码如下:
/**
* @author ycw
* @deprecated 数据迁移
* @date 2022/04/28
*/
@Slf4j
@Service("dataService")
public class DataServiceImpl extends ServiceImpl<DataMapper, DataEntity> implements DataService {
@Autowired
private DataMapper dataMapper;
@Autowired
private DataSource dataSource;
@Override
public BaseResult<Integer> 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;
}
}
}
`
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)