【发布时间】:2017-09-19 07:31:16
【问题描述】:
所以我尝试创建一个 JTable,它通过 JBDC 连接到 SQL server 数据库,并具有插入、删除和编辑数据等功能。它适用于插入但更新、删除。你们能告诉我为什么我得到ArrayIndexOutOfBoundsException: -1 以及如何解决它。这是我的代码。这里的书是一个扩展JFRAME的类
public Book() {
initComponents();
model.addColumn("ID");
model.addColumn("Name");
model.addColumn("Type");
jTable1.setModel(model);
displayTable();
jTable1.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
int row = jTable1.getSelectedRow();
txtName.setText(jTable1.getValueAt(row, 1).toString());
txtType.setText(jTable1.getValueAt(row, 2).toString());
}
});
}
public void displayTable() {
try {
model.setRowCount(0);
ConnectToSQL sql = new ConnectToSQL();
connection = sql.getConnection();
st = connection.createStatement();
ResultSet result = st.executeQuery("SELECT * FROM BOOK");
while (result.next()) {
model.addRow(new Object[]{result.getInt("id"), result.getString("name"), result.getString("type")});
}
} catch (SQLException ex) {
Logger.getLogger(Book.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int row = jTable1.getSelectedRow();
String id = jTable1.getValueAt(row, 0).toString();
try {
// TODO add your handling code here:
st.executeUpdate("Update Book set name ='" + txtName.getText() + "',type='" + txtType.getText() + "' where id =" + id);
displayTable();
} catch (SQLException ex) {
Logger.getLogger(Book.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int row = jTable1.getSelectedRow();
String id = jTable1.getValueAt(row, 0).toString();
try {
// TODO add your handling code here:
st.executeUpdate("Delete from book where id =" + id);
displayTable();
} catch (SQLException ex) {
Logger.getLogger(Book.class.getName()).log(Level.SEVERE, null, ex);
}
}
【问题讨论】:
-
在哪一行?你得到这个错误
-
在 btnUpdateActionPerformed 和 btnDeleteActionPerformed 我得到了 ArrayIndexOutOfBoundsException,即使它仍然删除或更新到数据库
-
好吧
-1当你没有选择一行时会发生这种情况。然后选择的行返回-1。例如如果row=-1然后jTable1.getValueAt(-1, 1)然后你得到错误。为避免这种情况,您可以查看if(row!=-1){//do something}else{//plz select a row}
标签: java sql-server swing jdbc indexoutofboundsexception