说明
今天测试预上线库时需要改表,先备份列Excel表格。
后发现有问题,需要还原某些数据,但是不是sql文件也不是sql语句。
这里是吧所有user_id 改为了-1,需要还原。
思路就是按照sql when then修改语句读取表里的id和user_id 去拼接sql,然后本地测试sql,再放到预上线执行。
数据格式:
执行:
public static void main(String[] args) {
hget();
}
/**
* 获取版本对应API
*/
public static Workbook getWorkbok(File file) throws IOException {
Workbook wb = null;
FileInputStream in = new FileInputStream(file);
if (file.getName().endsWith(".xls")) { //Excel 2003
wb = new HSSFWorkbook(in);
} else if (file.getName().endsWith(".xlsx")) { // Excel 2007/2010
wb = new XSSFWorkbook(in);
}
in.close();
return wb;
}
/**
* 读取文件,拼接sql
* sout:
* update material_group set user_id = (case
* when id = 341 then 609
* when id = 342 then 611
* when id = 343 then 611
* when id = 344 then 621
* when id = 345 then 621
* end) where id < 714
* 关于sql,这里的where如果不写则会遍历表把所有数据更新掉,所以 1、备份 2、加条件!
*/
private static void hget() {
try {
//拼接sql
String sql = "update material_group set user_id = (case ";
//文件地址
String path = "/Users/ghostSugar/Downloads/query_result_2021-04-22T01_31_15.058095Z.xlsx";
File file = new File(path);
Workbook workbook = getWorkbok(file);
Sheet sheet = workbook.getSheetAt(0);
int i = 0;
Row row = null;
Cell cell = null;
StringBuilder sb = new StringBuilder();
//获取行
while ((row = sheet.getRow(i)) != null) {
i++;
int j = 0;
//获取列内容
while ((cell = row.getCell(j)) != null) {
j++;
if (i > 1 ) {
if (j == 1) {
String id = cell.toString();
sb.append(" when id = ").append(id.substring(0, id.lastIndexOf("."))).append(" ");
}
if (j == 2) {
String userId = cell.toString();
sb.append(" then ").append(userId.substring(0, userId.lastIndexOf("."))).append(" ");
}
}
System.out.println(String.format("第%n行 第%n列 cell:%s", i, j, cell));
}
}
sql = sql + sb.toString() + "end) where id < 714";
System.out.println("sql:" + sql);
} catch (Exception e) {
e.printStackTrace();
}
}
以上。