initComponents();
try {
ResultSet res = statement.executeQuery("SELECT * FROM banh");
ResultSetMetaData RSMD = res.getMetaData();
NumberOfColumns = RSMD.getColumnCount();
AttributeNames = new String[NumberOfColumns];
for(int i=0;i<NumberOfColumns;i++)
AttributeNames[i]=RSMD.getColumnName(i+1);
MyArray=new Object[10000][NumberOfColumns];
int R=0;
while(res.next()) {
for(int C=1; C<=NumberOfColumns;C++)
MyArray[R][C-1]=res.getObject(C);
R++;
}
res.close();
NumberOfRows=R;
Object[][] TempArray=MyArray;
MyArray=new Object[NumberOfRows][NumberOfColumns];
for(R=0;R<NumberOfRows;R++)
for(int C=0;C<NumberOfColumns;C++)
MyArray[R][C]=TempArray[R][C];
TableData.setModel(new MyTableModel());
TableData.setVisible(true);
}
catch(Exception e)
{
e.printStackTrace();
}
public void initComponents()
{
model = new DefaultTableModel (new Object [][]
{
{null},
{null},
{null},
{null}
},
new String [] {""}
) {
Class[] types = new Class [] {java.lang.Object.class};
boolean[]canEdit=new boolean[]{false};
public Class getColumnClass(int columnIndex)
{
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex)
{
return canEdit [columnIndex];
}
};
TableData.setModel(model);
JScrollPane ScrollPane1 = new JScrollPane(TableData);
ScrollPane1.setBounds(30,170,950,290);
Frame.add(ScrollPane1,BorderLayout.CENTER);
}
I show my Database to JTable by this way, I found it on Internet, it's not mine and it's work. But now I don't know how to add row to JTable and Database, I've found many website but no use (PreparedStatement, executeUpdate...). Can anyone help me about this because I've just learnt. Thank You !
That is a poor example to use:
Instead check out the
Table From Database Example
code found in Table From Database. This example uses Vectors which will grow depending on the number of rows found in the ResultSet.You can use the
addRow(...)
method of theDefaultTableModel
to add data dynamically. Read the API or search the forum/web for examples that use the addRow(...) method.For database inserts you can start with the tutorial on JDBC Database Access.