且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何插入,更新和删除从(SQLite)数据库加载的JTable中的项目

更新时间:2023-12-03 14:59:34

我仍然不清楚你的要求,对象使用一个表模型对象来表示一个表模型对象,它包含一个表模型对象。管理实际表数据。表模型对象必须实现 TableModel 接口。然而, DefaultTableModel 它自己就足以处理表数据交互。查看 java doc 了解更多然而,为了检测对由表模型对象管理的数据所做的更改, c> model 与关联JTable 实例需要注册到的实现 c> TableModelListener 使用 addTableModelListener()函数。将使用事件 TableModelEvent e 通知侦听器以检查数据行中的更改和更改类型:




  • e.getFirstRow():返回更改的第一行的索引,包括 TableModelEvent.HEADER_ROW

  • e.getLastRow():更改的最后一行

  • e.getType():更改的单元格发生了什么:

    1. 插入的行: e.getType()== TableModelEvent.INSERT

    2. 已删除: e.getType()== TableModelEvent.DELETE

    3. >: e.getType()== TableModelEvent.UPDATE。




A short example:

  model.addTableModelListener new TableModelListener(){

@Override
public void tableChanged(TableModelEvent e){
int rowFirstIndex = e.getFirstRow();
int rowLastIndex = e.getLastRow();

DefaultTableModel model =(DefaultTableModel)e.getSource();
if(e.getType()== TableModelEvent.UPDATE)
{
int updatedColIndex = e.getColumn();
String updateColmn = table.getColumnName(updatedColIndex);
String updatedValue =(String)model.getValueAt(rowFirstIndex,updatedColIndex);
System.out.println(column:+ updateColmn +value:+ updatedValue);
updateDB(updateColmn,updatedValue);
}

else if(e.getType()== TableModelEvent.INSERT)
{
for(int i = rowFirstIndex; i {
Vector rowData =(Vector)model.getDataVector()。get(i);

Map< String,String> dataMap = new HashMap<>();

for(int j = 0; j< rowData.size(); j ++)
dataMap.put(table.getColumnName(j),(String)rowData.get );

InsertToDB(dataMap); //现在它包含对应于行值的columndName

}
}
}
});

编辑(根据您的评论)我得到[value1,value2,value3]。我如何使用这个与我的SQL语句?



如果您有兴趣映射行值与列名称,用于构建SQL查询语法:向量包含具有维护索引的行数据。也就是说, row.get(i)有列索引 i 的数据。您可以使用 table.getColumnName(i)获取对应于行向量的索引 i 处的列名称值 i



教程:


  1. 如何编写表模型侦听器


    1. I currently have 2 classes, one displaying the GUI and one is to get items from the database. My code is as follows:

      This code is to display the JTable in my GUI

      public void table() {
          if(SOMR.tableCall() == true) {
              this.columnNames = SOMR.getCol();
              this.data = SOMR.getData();
          JTable table = new JTable(data, columnNames)
          {
              public Class getColumnClass(int column)
              {
      
                  for (int row = 0; row < getRowCount(); row++)
                  {
                      Object o = getValueAt(row, column);
      
                      if (o != null)
                      {
                          return o.getClass();
                      }
                  }
      
                  return Object.class;
              }
          };
      
          JScrollPane scrollPane = new JScrollPane( table );
          add( scrollPane, BorderLayout.CENTER );
          }
      
      }
      

      and this code is to retrieve the items and pass them to the above codes to display the items retrieved to the JTable

      public boolean table() {
      
          Connection connection = null;  
           ResultSet resultSet = null;  
           PreparedStatement preparedStatement = null;  
           try 
           {  
               Class.forName("org.sqlite.JDBC");  
               connection = DriverManager.getConnection("jdbc:sqlite:db");
               preparedStatement = connection.prepareStatement("SELECT item1, item2, item3 FROM menu WHERE can = ? AND id = ?");
               preparedStatement.setInt(1, can);
               preparedStatement.setInt(2, id);
               resultSet =  preparedStatement.executeQuery();
               ResultSetMetaData md = resultSet.getMetaData();
               columns = 3;//md.getColumnCount();
               for(int i = 1; i<=columns; i++) {
                   columnNames.addElement(md.getColumnName(i));
               }
               while(resultSet.next()) {
                   row = new Vector(columns);
                   for (int i = 1; i<=columns; i++) {
                       row.addElement(resultSet.getObject(i));
                   }
                   data.addElement(row);
               }
               tablecall = true;
               return tablecall;
           }
           catch (Exception ex) 
           {  
               tablecall = false;
               ex.printStackTrace();  
           }
           finally 
           {  
               try 
               {  
                   resultSet.close();  
                   preparedStatement.close();  
                   connection.close();  
               } 
               catch (Exception ex) 
               {  
                   ex.printStackTrace();  
               }  
           }
          return tablecall;
      }
      

      I have followed the way of displaying the JTable from Table From Database, however I do not really know how to go about inserting, updating and deleting a row from the JTable and update in the database, then refresh the JTable to display from the newly updated database.

      I would like to add an 'add item' button, then it will popup a frame/window with fields to enter, then after clicking 'add' in the popup frame, the JTable and the database will be updated at the same time.

      Could anyone please help me in this? I'm lost.. Thank you very much!

      I am still unclear about your requirements, but lets start answering as much as i have got to:

      Every JTable object uses a table model object to manage the actual table data. A table model object must implement the TableModel interface. However the DefaultTableModel it self is enough to work with table data interaction. Check out it's java doc for more details.

      However, To detect changes to the data managed by a table model object, the model associating with JTable instance needs to get registered to an implementation of TableModelListener interface using addTableModelListener() function. The listener will be notified with an event TableModelEvent e to inspect the changes in data rows and the type of changes using:

  • e.getFirstRow(): Return the index of the first row that changed, including the table header which is specified by TableModelEvent.HEADER_ROW
  • e.getLastRow(): The last row that changed
  • e.getType(): What happened to the changed cells:
    1. If data rows inserted: e.getType() == TableModelEvent.INSERT
    2. If data rows deleted: e.getType() == TableModelEvent.DELETE
    3. If data rows updated: e.getType() == TableModelEvent.UPDATE.

A Short example:

model.addTableModelListener(new TableModelListener() {

     @Override
     public void tableChanged(TableModelEvent e) {
          int rowFirstIndex = e.getFirstRow();
          int rowLastIndex = e.getLastRow();

          DefaultTableModel model = (DefaultTableModel) e.getSource();
           if(e.getType()==TableModelEvent.UPDATE)
            {
                int updatedColIndex = e.getColumn();
                String updateColmn = table.getColumnName(updatedColIndex);
                String updatedValue = (String) model.getValueAt(rowFirstIndex, updatedColIndex);
                System.out.println("column: "+updateColmn+" value: "+updatedValue);
                updateDB(updateColmn, updatedValue);
            }

            else if(e.getType()==TableModelEvent.INSERT)
            {
             for(int i= rowFirstIndex; i <= rowLastIndex ; i++)  
              {   
                  Vector rowData = (Vector) model.getDataVector().get(i);

                  Map<String, String>dataMap = new HashMap<>();

                  for(int j=0; j < rowData.size() ; j++)
                    dataMap.put(table.getColumnName(j), (String) rowData.get(j));

                  InsertToDB(dataMap); // now it contains columndName corresponding to row value

              }
          }
         }
     });

Edit (on per your comment) : I am getting [value1, value2, value3]. How do I then use this with my SQL statement?

If you are interested to map the row value with column name, as is the case for building SQL query syntax: the vector contains the row data with maintaining column index. That is the row.get(i) has the data with column index i. You can use table.getColumnName(i) to get the name of the column at index i corresponding to the row vector value at index i.

Tutorial:

  1. How to write a table model listener