问题
I created a Jtable using Netbeans 7.1. The table created a default model as below
table.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
I also added the following lines of code to populate data from an Sqlite Database.
public void tabl()
{
try
{
stmt=conn.createStatement();
String sql2="SELECT * FROM students";
rs=stmt.executeQuery(sql2);
int n=0;
while(rs.next())
{
table.setValueAt(rs.getString(1),n,0);
table.setValueAt(rs.getString(2),n,1);
table.setValueAt(rs.getString(3),n,2);
table.setValueAt(rs.getString(4),n,3);
n++;
}
}
catch(SQLException e)
{
}
}
My quiz is How do I now make the JTable able to Update and delete records...with the default model.I am new to table Models.
回答1:
DefaultTableModel dmReset = (DefaultTableModel) table.getModel();
try {
stmt=conn.createStatement();
String sql2="SELECT * FROM students";
rs=stmt.executeQuery(sql2);
while (rs.next()) {
Vector v = new Vector();
v.add(rs.getString(1));
v.add(rs.getString(2));
v.add(rs.getString(3));
v.add(rs.getString(4));
dmReset.addRow(v);
}
} catch (Exception e) {
System.err.println(e.toString());
}
Note : Use full column headers in rs.getXXX() methods instead of column indexes.
for more details on TableModel you can refer this document.
If you want to get other types of data like Float, int etc... a switch case can be added with this, you can find example here.
回答2:
you have to create statement like this
conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
and also note that select * FROM table; always returns read only result set. instead query should be select column1,columnn FROM table;
来源:https://stackoverflow.com/questions/9470240/modifying-records-into-database-through-jtable