亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

java怎么將excel導入數據庫

小億
93
2023-11-08 13:59:19
欄目: 編程語言

要將Excel導入數據庫,可以使用Java中的Apache POI庫來讀取Excel文件,然后使用JDBC連接到數據庫并將數據插入到數據庫中。
以下是一個簡單的示例代碼:

import java.io.FileInputStream;
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 ExcelToDatabase {

????public?static?void?main(String[]?args)?{

????????String?excelFilePath?=?“path/to/excel/file.xlsx”;

????????String?url?=?“jdbc:mysql://localhost:3306/database_name”;

????????String?username?=?“username”;

????????String?password?=?“password”;

????????try?(Connection?connection?=?DriverManager.getConnection(url,?username,?password))?{

????????????FileInputStream?inputStream?=?new?FileInputStream(excelFilePath);

????????????Workbook?workbook?=?new?XSSFWorkbook(inputStream);

????????????Sheet?sheet?=?workbook.getSheetAt(0);

????????????String?insertQuery?=?"INSERT?INTO?table_name?(column1,?column2,?column3)?VALUES

?????????????(?,??,??)";

????????????PreparedStatement?statement?=?connection.prepareStatement(insertQuery);

????????????for?(int?i?=?1;?i?<=?sheet.getLastRowNum();?i++)?{

????????????????Row?row?=?sheet.getRow(i);

????????????????Cell?cell1?=?row.getCell(0);

????????????????Cell?cell2?=?row.getCell(1);

????????????????Cell?cell3?=?row.getCell(2);

????????????????String?value1?=?cell1.getStringCellValue();

????????????????String?value2?=?cell2.getStringCellValue();

????????????????String?value3?=?cell3.getStringCellValue();

????????????????statement.setString(1,?value1);

????????????????statement.setString(2,?value2);

????????????????statement.setString(3,?value3);

????????????????statement.executeUpdate();

????????????}

????????????workbook.close();

????????????System.out.println(“Excel?imported?to?database?successfully!”);

????????}?catch?(Exception?e)?{

????????????e.printStackTrace();

????????}

????} }

請確保已添加Apache POI和MySQL JDBC驅動的依賴項。在代碼中,需要將path/to/excel/file.xlsx替換為實際的Excel文件路徑,jdbc:mysql://localhost:3306/database_name替換為實際的數據庫連接URL,usernamepassword替換為實際的數據庫用戶名和密碼,table_name替換為實際的數據庫表名,column1column2column3替換為實際的數據庫表列名。

0
郸城县| 太保市| 额济纳旗| 昂仁县| 翁源县| 嵊州市| 临海市| 景洪市| 铁岭县| 资中县| 宁城县| 永年县| 卫辉市| 乌兰察布市| 广饶县| 涪陵区| 辽阳市| 改则县| 定边县| 台湾省| 通州市| 汉沽区| 上思县| 兰州市| 仙桃市| 扬州市| 竹溪县| 平安县| 资阳市| 章丘市| 清镇市| 西乡县| 阳朔县| 阳新县| 秭归县| 新源县| 东方市| 右玉县| 玛纳斯县| 马山县| 永清县|