21xrx.com
2025-03-25 02:53:36 Tuesday
文章检索 我的文章 写文章
作为一名JAVA开发者
2023-06-11 00:58:45 深夜i     --     --

作为一名JAVA开发者,我经常会遇到需要将数据从excel导入到MySQL数据库的需求。这个过程涉及到很多细节和技巧,今天我就来分享一下我的操作经验。

首先,我们需要打开excel文件并读取其中的数据。JAVA中,我们可以使用Apache POI这个库来实现这个功能。具体代码如下:

FileInputStream inputStream = new FileInputStream(new File("file.xlsx"));
// 创建一个工作簿
Workbook workbook = new XSSFWorkbook(inputStream);
// 获取第一个Sheet表格
Sheet sheet = workbook.getSheetAt(0);
// 遍历Sheet表格中的数据
for (Row row : sheet) {
  for (Cell cell : row) {
    // 输出每个单元格中的数据
    System.out.print(cell.toString() + "\t");
  }
  System.out.println();
}
// 关闭输入流和工作簿
inputStream.close();
workbook.close();

接下来,我们需要将读取到的数据插入到MySQL数据库中。JAVA中,我们可以使用JDBC来实现这个功能。具体代码如下:

// 加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 连接数据库
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC",
        "root", "password");
// 创建一个Statement对象
Statement statement = connection.createStatement();
// 插入数据的SQL语句
String sql = "INSERT INTO `table_name`(`column_name1`, `column_name2`, ...) VALUES (?, ?, ...);";
// 遍历Sheet表格中的数据
for (Row row : sheet) {
  // 创建一个PreparedStatement对象
  PreparedStatement preparedStatement = connection.prepareStatement(sql);
  for (int i = 0; i < row.getLastCellNum(); i++) {
    // 设置每个占位符的值
    preparedStatement.setString(i + 1, row.getCell(i).toString());
  }
  // 执行SQL语句
  preparedStatement.executeUpdate();
  // 关闭PreparedStatement对象
  preparedStatement.close();
}
// 关闭Statement对象和连接
statement.close();
connection.close();

以上就是我在JAVA中将excel数据导入到MySQL数据库的经验分享,希望能对需要的读者有所帮助。

  
  

评论区