帮我写一段JAVA代码实现从表格文件中读取数据批量导入数据库
时间: 2024-02-11 18:03:57 浏览: 90
好的,以下是一个简单的 JAVA 代码示例,可以从表格文件中读取数据批量导入数据库:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ImportDataFromExcel {
public static void main(String[] args) {
String jdbcUrl = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
String excelFilePath = "path/to/excel/file.xlsx";
String tableName = "mytable";
try (Connection connection = DriverManager.getConnection(jdbcUrl, username, password);
FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
Workbook workbook = new XSSFWorkbook(inputStream)) {
Sheet sheet = workbook.getSheetAt(0);
String sql = "INSERT INTO " + tableName + " (column1, column2, column3) VALUES (?, ?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
int batchSize = 20;
int count = 0;
for (Row row : sheet) {
if (count == 0) {
count++;
continue;
}
Cell cell1 = row.getCell(0);
String column1 = cell1.getStringCellValue();
Cell cell2 = row.getCell(1);
int column2 = (int) cell2.getNumericCellValue();
Cell cell3 = row.getCell(2);
double column3 = cell3.getNumericCellValue();
statement.setString(1, column1);
statement.setInt(2, column2);
statement.setDouble(3, column3);
statement.addBatch();
if (count % batchSize == 0) {
statement.executeBatch();
}
}
statement.executeBatch();
System.out.println("Data imported successfully.");
} catch (IOException | SQLException e) {
e.printStackTrace();
}
}
}
```
这段代码使用了 Apache POI 库来读取 Excel 文件中的数据,然后使用 JDBC 连接数据库,并使用 PreparedStatement 批量插入数据到数据库中。你需要将代码中的 `jdbcUrl`、`username`、`password`、`excelFilePath` 和 `tableName` 替换为你自己的数据库连接信息和 Excel 文件路径以及表名。同时,你还需要在代码中根据实际情况修改 SQL 插入语句以及表格文件中的列名和数据类型。
阅读全文