import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.*;
import cn.hutool.core.util.ReUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.stereotype.Component;
public class changeDatabaseThroughExcel {
private static String filePath = "C:\\Users\\idmin\\Desktop\\文件名称";
private static String url = "jdbc:mysql://数据库地址?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC";
private static String user = "数据库用户";
private static String password = "数据库密码";
public static void main(String [] args) throws Exception {
//声明Connection对象
Connection con = null;
PreparedStatement us = null;
InputStream is = null;
//遍历查询结果集
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection(url,user,password);
if(con.isClosed())
System.out.println("连接数据库失败");
us = con.prepareStatement("执行的sql语句");
is = new FileInputStream(filePath);
HSSFWorkbook excel = new HSSFWorkbook(is);
HSSFSheet sheet = excel.getSheetAt(0);
int idIndex = 0;
for(Row row :sheet){
for(Cell cell:row){
cell.setCellType(cell.CELL_TYPE_STRING);//不推荐使用的方法,但是取出列有数字的话,要转换一下
if(!StringUtils.isBlank(cell.getStringCellValue())){
if(ReUtil.contains("列名",cell.getStringCellValue())){
idIndex = cell.getColumnIndex();
}
}
}
}
//遍历每行,得到指定列
for(Row row :sheet){
if(!StringUtils.isBlank(row.getCell(idIndex).getStringCellValue())){
if(!ReUtil.contains("列名",row.getCell(idIndex).getStringCellValue())){
//给sql语句中的占位符赋值
us.setString(1, row.getCell(idIndex).getStringCellValue());
int result = us.executeUpdate();
if(result==1){
System.out.println("修改成功:" + row.getCell(index).getStringCellValue());
}else{
System.out.println("修改失败:" + row.getCell(index).getStringCellValue());
}
}
}
}
} catch(ClassNotFoundException e) {
e.printStackTrace();
} catch(SQLException e) {
//数据库连接失败异常处理
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}finally{
//关闭输入流
if(is!=null){
is.close();
}
if(us!=null){
us.close();
}
if(con!=null){
con.close();
}
}
}
}