我的任务是从 Excel 表中获取数据并在 MySQL 数据库中更新,该数据库有 2 列 USN 和 Name。问题是 USN 在行和名称中都打印。例如,如果我将它保存在数据库中时有 12 条记录,它将插入 24 条记录。我也在使用 Swing 概念。下面是我的代码。
class OpenClass implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Workbook w ;
chooser = new JFileChooser();
JFileChooser chooser = new JFileChooser();
int option = chooser.showOpenDialog(ExcelFileUploading.this);
if(option == JFileChooser.APPROVE_OPTION)
{
try
{
w = Workbook.getWorkbook(chooser.getSelectedFile());
Sheet sheet = w.getSheet(0);
for(int i = 0; i<sheet.getRows(); i++)
{
for(int j=0; j<sheet.getColumns();j++)
{
Cell cell = null;
if(j==0)
{
cell = sheet.getCell(j, i);
if(checkIfNumber(cell.getContents().toString())== false)
{
//System.out.print("\t\t");
continue;
}
System.out.print("\n");
}
cell = sheet.getCell(j, i);
CellType type = cell.getType();
if((type == CellType.LABEL)|| (type == CellType.NUMBER))
{
try
{
Class.forName(driver);
con = DriverManager.getConnection(url+dbName,username,password);
stmt = con.createStatement();
String query = "INSERT INTO student (USN,Name)"
+"VALUES('"+cell.getContents()+"','"+cell.getContents()+"')";
stmt.executeUpdate(query);
} catch (Exception exp)
{
exp.printStackTrace();
}
finally
{
try
{
stmt.close();
con.close();
} catch (SQLException exp)
{
}
}
}
}
}
} catch (Exception exp)
{
exp.printStackTrace();
}
display.setText("Opened File : " +((chooser.getSelectedFile()!=null)?
chooser.getSelectedFile().getName(): "nothing"));
}
if(option == JFileChooser.CANCEL_OPTION)
{
display.setText("Open Operation Cancelled");
}
}
private boolean checkIfNumber(String string)
{
try
{
double d = Double.parseDouble(string);
//System.out.print(d);
return true;
} catch (NumberFormatException ne)
{
return false;
}
}
}
由于我的 Db 表中有 2 列(USN,名称),我不得不放cell.getContents()
两次。
谁能帮我?