我有一个 H2 数据库,我想从 JTable
读取记录来填充数据库表。但是我的表可以有空记录。
我正在使用这个方法:
String descr = jTable2.getValueAt(i, 1).toString();
每当 JTable
(i, 1) 中的字段为空时,我都会收到此错误:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException.
有什么建议如何从表中读取和存储空值而不出现此错误吗?
编辑: 对于更明确的示例,每当我在空字段中执行 jTable2.getValueAt(i, 1) 时,都会发生相同的 null 异常..
for (int i = 0; i <10; i++) {
int processos = Integer.parseInt(jTable2.getValueAt(i, 0).toString());
String descr = jTable2.getValueAt(i, 1).toString();
if(!descr.isEmpty())
descr = jTable2.getValueAt(i, 1).toString();
else{
descr= "";
}
//String data = jTable2.getValueAt(i, 2).toString();
System.out.println(processos + descr);
try {
databaseManager.saveTable(intIDinternto, processos, descr, "aaaa");
} catch (SQLException ex) {
Logger.getLogger(MainView.class.getName()).log(Level.SEVERE, null, ex);
}
解决方案:先使用对象,然后解析为字符串并进行比较。
for (int i = 0; i <10; i++) {
String description = " ";
int processos = Integer.parseInt(jTable2.getValueAt(i, 0).toString());
Object descr = jTable2.getModel().getValueAt(i, 1);
if (descr!= null)
description = jTable2.getModel().getValueAt(i, 1).toString();
else
description = ".";
//String data = jTable2.getValueAt(i, 2).toString();
System.out.println(processos + description);
try {
databaseManager.saveTable(intIDinternto, processos, description, "aaaa");
} catch (SQLException ex) {
Logger.getLogger(MainView.class.getName()).log(Level.SEVERE, null, ex);
}
最佳答案
您必须进行检查,例如:
String descr = jt.getValueAt(0, 1).toString();
int storedValue = 0;
//check if your value is a correct integer or not
if (descr.matches("\\d+")) {
storedValue = Integer.parseInt(descr);
} else {
System.out.println("Exception");
}
System.out.println(storedValue);
想法:使用正则表达式检查您的值是否正确 descr.matches("\\d+")
如果输入正确,那么您可以解析它,否则您不能,您必须抛出异常或其他任何事情
关于java - JTable读取空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43633496/