我已经从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我不知道如何存储在DB
中请告诉我如何使用JDBC
将数据存储到mysql数据库中提前完成
答案 0 :(得分:3)
如果您要在其中添加单元格值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
}
我还建议您查看此MySQL and Java JDBC - Tutorial