我正在尝试将xls
文件导入mysql
,但收到错误Nullpointer EXCEPTION
请给我解决方案
package abhi;
public class ImportData {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/test","root","abhi1402");
con.setAutoCommit(false);
PreparedStatement pstm = null ;
FileInputStream input = new FileInputStream("D:/New Folder/apnakhata1.xls");
POIFSFileSystem fs = new POIFSFileSystem( input );
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
Row row;
for(int i=1; i<=sheet.getLastRowNum(); i++){
row = sheet.getRow(i);
String CountryName = row.getCell(1).getStringCellValue();
String CountryCode = row.getCell(2).getStringCellValue();
String BankName = row.getCell(3).getStringCellValue();
String Website = row.getCell(4).getStringCellValue();
String Name = row.getCell(5).getStringCellValue();
String SMS = row.getCell(6).getStringCellValue();
int SMSNumber = (int) row.getCell(7).getNumericCellValue();
int CustomerCare = (int) row.getCell(8).getNumericCellValue();
String sql = "INSERT INTO Bank VALUES('"+CountryName+"','"+CountryCode
+"','"+BankName+"','"+Website+"','"+Name+"','"+SMS+"','"+SMSNumber
+"','"+CustomerCare+"')";
pstm = (PreparedStatement) con.prepareStatement(sql);
pstm.execute();
System.out.println("Import rows "+i);
}
con.commit();
pstm.close();
con.close();
input.close();
System.out.println("Success import excel to mysql table");
}catch(ClassNotFoundException e){
System.out.println(e);
}catch(SQLException ex){
System.out.println(ex);
}catch(IOException ioe){
System.out.println(ioe);
}
}
}
}
}
答案 0 :(得分:0)
您的代码中NullPointerException
的原因归于
for(int i=1; i<=sheet.getLastRowNum(); i++)
检查您的Excel文件。它可能包含一些空白行或可能是一些空白列值,然后运行您的代码。
答案 1 :(得分:0)
你必须把
String CountryName = row.getCell(0).getStringCellValue();
String CountryCode = row.getCell(1).getStringCellValue();
String BankName = row.getCell(2).getStringCellValue();
String Website = row.getCell(3).getStringCellValue();
String Name = row.getCell(4).getStringCellValue();