2013-04-01 56 views
0

你好,我有这个问题..任何人都可以给我摘录吗?我有MySql的表显示JList项目,所以我可以很容易地添加项目,但无法从数据库中删除它?同时按删除项目?从jList的数据库中删除记录的问题

我搜索了很多没有人需要做..我不知道它有可能吗?

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {            
    try { 
     Class.forName("com.mysql.jdbc.Driver"); 
     Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","ubuntu123"); 

     PreparedStatement stmt = null; 
     ResultSet rs = null; 

     String [] data; 
     data = new String[100]; 
     int i=0; 

     DefaultListModel listmodel = (DefaultListModel) jList2.getModel(); 
     int selectedIndex = jList2.getSelectedIndex(); 
     if (selectedIndex != -1) { 
      listmodel.remove(selectedIndex); 

      String query = "delete from supplierinfo where companyname = ?"; 
      stmt = (PreparedStatement) con.prepareStatement(query); 
      stmt.setInt(1, i); 
      stmt.execute(); 

      con.close(); 

      // i= i+1; 
     } 
    } catch(Exception e) { 
     System.out.println("3rd catch " +e); 
    } 
}           
+0

实际的问题是什么? – CAMOBAP

+0

可能的重复[我有JList并试图从数据库中删除项目,但不删除一个项目将删除整个记录](http://stackoverflow.com/questions/15716752/i-have-the-jlist-and -trying-remove-item-from-database-but-instead-of-removing) – kleopatra

+0

它不会一次又一次询问完全相同的问题。相反,试着理解你已经给出的答案,然后... *关注他们。 – kleopatra

回答

0

对当前选定的索引使用ListModel#getElementAt(int)方法。

如果您确定您的模型只包含字符串的情况下,你可以直接将其转换为一个字符串,然后用这个字符串替换istmt.setInt(1, i);

1

您可以在一个变量保存元素,当你从ListModel删除它。

之后,您可以获取有关此项目的所有重要信息,并在查询中使用它。

使用这样的事情:

YourObjectType obj = (YourObjectType) listmodel.remove(selectedIndex);

String query = "delete from supplierinfo where companyname = ?"; 
        stmt = (PreparedStatement) con.prepareStatement(query); 
        stmt.setInt(1, obj.getCompanyName()); 
        stmt.execute();