【发布时间】:2013-02-01 09:50:23
【问题描述】:
我的任务是从 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()。
谁能帮帮我?
【问题讨论】:
-
你是如何读取excel文件的?我的猜测是你读错了excel文件。还使用准备好的语句进行数据库查询
-
如果我在控制台中按我想要的方式打印,那么读取所有内容都是正确的 bcz。就好像我插入 Db 一样,它给出了上述问题
-
你能给我们看一个你的excel表格的小例子吗?有多少列?内容是什么?
-
我可以上传图片,但不能。它的 k 我的 excel 表有 2 列 一列 USN 另一列名称
-
@Rithesh:一张便条。您正在为循环中的每个迭代创建一个单独的连接。这对性能来说太重了