如何使用jdbc连接将excel表单中的数据存储到mysql数据库中

我已经写了从Excel工作表访问数据的代码,但我不能使用JDBC存储到数据库。 我从Excel表访问数据的代码

try{ List list=new ArrayList(); String fileName="d:\\menu.xls"; File file=new File(fileName); InputStream input = new BufferedInputStream(new FileInputStream(file)); POIFSFileSystem fs = new POIFSFileSystem( input ); HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFSheet sheet = wb.getSheetAt(0); //int i=0; Iterator rows=sheet.rowIterator(); while(rows.hasNext()){ HSSFRow row=(HSSFRow)rows.next(); System.out.println("\n"); Iterator cells=row.cellIterator(); while( cells.hasNext() ) { HSSFCell cell = (HSSFCell) cells.next(); if(HSSFCell.CELL_TYPE_NUMERIC==cell.getCellType()){ System.out.print(cell.getNumericCellValue()+" " ); // list.add(cell.getNumericCellValue()); } else if (HSSFCell.CELL_TYPE_STRING==cell.getCellType()){ System.out.print(cell.getStringCellValue()+" " ); //list.add(cell.getStringCellValue()); } else if (HSSFCell.CELL_TYPE_BOOLEAN==cell.getCellType()){ System.out.print(cell.getBooleanCellValue()+" " ); //list.add(cell.getBooleanCellValue()); } else if(HSSFCell.CELL_TYPE_BLANK==cell.getCellType()){ System.out.print( "BLANK " );} else System.out.print("Unknown cell type"); } } System.out.println(list); }catch(Exception e){ e.printStackTrace(); } 

我把所有的数据到myeclipse控制台bt我不知道如何存储在数据库中

请告诉我如何使用JDBC将数据存储到mysql数据库中

提前感谢

由于您有一个ArrayList ,您可以在其中添加单元格值,您可以按如下所示进行操作:

 public void insertRowInDB(List cellValues){ Connection con = null; PreparedStatement preparedStatement = null; try{ Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost/databaseName?" + "user=sqlUser&password=sqlPassword"); String sql = "INSERT INTO tableName(field1, field2, ..., fieldN) VALUES (?,?,...,?)"; preparedStatement = con.prepareStatement(sql); int paramIndex = 1; for(Object cell : cellValues){ preparedStatement.setObject(paramIndex, cell); paramIndex++; } int status = preparedStatement.executeUpdate(); //DO something with the status if needed } catch(SQLException ex) { /* log the exception */ } finally { try{ preparedStatemnt.close(); con.close(); } catch(SQLException ignored) {} } } 

你需要做这个小小的改变:

 while(rows.hasNext()){ List list = new ArrayList(); // initialize the list here HSSFRow row=(HSSFRow)rows.next(); System.out.println("\n"); Iterator cells=row.cellIterator(); while( cells.hasNext() ) { /* all your code seems fine here, just uncomment list.add(something) lines */ } insertRowInDB(list); // insert the cells in your database } 

我也build议你看看这个MySQL和Java JDBC – 教程