当我运行以下代码时,出现错误:
java.lang.String无法强制转换为java.lang.Integer
这是我的代码:
try{
int rows = jTable1.getRowCount();
String myUrl = "jdbc:mySql://localhost:3306/hospital";
Connection con = DriverManager.getConnection(myUrl,"root","");
con.setAutoCommit(false);
String query = "Insert into `test and treatment_has_admission`(`Test and Treatment_id`,`Admission_a_id`,`Test_Result`,`Treatment_Result`,`Date`)"+" values (?, ?, ?, ?, ?)";
PreparedStatement pst = con.prepareStatement(query);
for(int row=0; row<rows; row++){
int TestTreatmentID = (int) jTable1.getValueAt(row, 1);
String test_result = (String) jTable1.getValueAt(row, 2);
String treatment_result = (String) jTable1.getValueAt(row, 3);
String Date = (String) jTable1.getValueAt(row, 4);
pst.setInt(1,TestTreatmentID);
pst.setInt(2,Integer.parseInt(t2.getText()));
pst.setString(3, test_result);
pst.setString(4, treatment_result);
pst.setString(5, Date);
pst.addBatch();
}
pst.executeBatch();
con.commit();
con.close();
}
catch(Exception e){
e.printStackTrace();
}
}
错误:java.lang.ClassCastException:java.lang.String不能 强制转换为java.lang.Integer
为什么我收到这样的错误?请帮我解决一下。
答案 0 :(得分:1)
String无法转换为Integer。使用此
int TestTreatmentID = Integer.parseInt(jTable1.getValueAt(row, 1));
修改强>
String string= jTable1.getValueAt(row, 1).toString();
int TestTreatmentID = Integer.parseInt(string);
答案 1 :(得分:0)
看来你在线上遇到了问题
int TestTreatmentID = (int) jTable1.getValueAt(row, 1);
让我们使用Integer.parseInt
代替
Integer TestTreatmentID = Integer.parseInt(jTable1.getValueAt(row, 1).toString());
答案 2 :(得分:0)
你不能简单地对这样的整数进行类型转换
int TestTreatmentID = (int) jTable1.getValueAt(row, 1);
相反,解析此字符串以获取正确的整数值
int TestTreatmentID = Integer.parseInt(jTable1.getValueAt(row, 1));
答案 3 :(得分:0)
您需要使用
将从方法返回的值解析为IntInteger.parseInt(jTable1.getValueAt(row, 1));