簡體   English   中英

如何創建數據庫以存儲我用Apache POI從excel文件讀取的數據?

[英]How to create database to store data that i read with Apache POI from excel files?

我使用APACHE POI從excel文件中讀取數據。 現在,我想用控制台中的結果創建數據庫。 我的Excel文件有6列8行。 誰能幫我? 我想找幾天的解決方案.. :(

對於簡單的應用程序,如果需要的話,可以使用JDBC即時創建數據庫並插入記錄。 否則,請先創建數據庫,然后在從excel文件讀取數據時插入行。

您要的東西有很多解決方案,您可以使用對象模型並將其與ORM工具配合使用。

我將從這里開始:

使用Apache Jakarta POI從Excel電子表格生成外部表

文章過時,因為他們將其稱為Jakarta POI,但這些概念可能會延續下去。 此外,即使它是基於Oracle的方法,您也可以進行概括。

如果您在此論壇中需要更具體的內容,則必須根據需求提供更具體的內容。

假設您正在以這種方式讀取內容,例如將值保存在列表中(取決於您的目的是字符串還是對象):

//Some code of yours here
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
HSSFRow row = (HSSFRow) rows.next();
Iterator cells = row.cellIterator();

List data = new ArrayList();
while (cells.hasNext()) {
HSSFCell cell = (HSSFCell) cells.next();
data.add(cell);
}

sheetData.add(data);

然后,如果您將數據保存在列表中,則指定數據庫引擎,例如MySQL:

static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
static final String DB_URL = "jdbc:mysql://localhost:3306/";
static final String USER = "username";
static final String PASS = "password";

然后,您繼續創建數據庫並插入記錄:

 Connection conn = null;
 Statement stmt = null;
Class.forName("com.mysql.jdbc.Driver");


 conn = DriverManager.getConnection(DB_URL, USER, PASS);

     System.out.println("About to create a database");
      stmt = conn.createStatement();
      String dbName = "MyExcelDB";
      String sql = "CREATE DATABASE " + dbName;
      stmt.executeUpdate(sql);
      System.out.println("Database created successfully...");
      //Now, create a table based on what you need, maybe you can get the headers of your excel
String tableName = "TBUSER";
String createTableSQL = "CREATE TABLE" + tableName + "("
                + "USER_ID NUMBER(5) NOT NULL, "
                + "USERNAME VARCHAR(20) NOT NULL, "
                + "CREATED_BY VARCHAR(20) NOT NULL, "
                + "CREATED_DATE DATE NOT NULL, " + "PRIMARY KEY (USER_ID) "
                + ")";
Statement createTableStatement = conn.createStatement();
createTableStatement.execute(createTableSQL);
//Now insert
String insertQuery = "insert into " + dbName + "." + tableName + "(user_id,username,created_by,created_date) values (?,?,?,?)";
PreparedStatement insertStatement = conn.prepareStatement(insertQuery);
insertStatement.setInt(1,Integer.parseInt(sheetData.get(0));
insertStatement.setString(2,sheetData.get(1));
//and so on... then
insertStatement.executeUpdate();//This returns an int, if the insert works, the value must be greater than 0

我知道代碼中有很多改進,但是我想為您提供實現的想法和“模板”。 最好的祝福。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM