I googled the whole day and no luck. I call getnPrintAllData()
method after pressing OK button. So the code is:
public class DatabaseSQLiteConnection {
Connection conn = null;
PreparedStatement statement = null;
ResultSet res = null;
public DatabaseSQLiteConnection(){
try{
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:test.sqlite");
statement = conn.prepareStatement("SELECT * from product_info;");
}
catch(Exception e){
e.printStackTrace();
}
}
public void getnPrintAllData(){
String name, supplier, id;
DefaultTableModel dtm = new DefaultTableModel();
Window gui = new Window(); //My JPanel class
try{
res = statement.executeQuery();
testResultSet(res);
ResultSetMetaData meta = res.getMetaData();
int numberOfColumns = meta.getColumnCount();
while (res.next())
{
Object [] rowData = new Object[numberOfColumns];
for (int i = 0; i < rowData.length; ++i)
{
rowData[i] = res.getObject(i+1);
}
dtm.addRow(rowData);
}
gui.jTable1.setModel(dtm);
dtm.fireTableDataChanged();
//////////////////////////
}
catch(Exception e){
System.err.println(e);
e.printStackTrace();
}
finally{
try{
res.close();
statement.close();
conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
public void testResultSet(ResultSet res){
try{
while(res.next()){
System.out.println("Product ID: "+ res.getInt("product_id"));
System.out.println("Product name: "+ res.getString("product_name"));
System.out.println("Supplier: "+ res.getString("supplier"));
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
My testResultSet()
method is working properly.
Now, how to change my code so that it works, or what is the most simple code to make DefaultTableModel
from ResultSet
?
Thanks in advance.
Edit: I am reciving java.lang.IllegalStateException: SQLite JDBC: inconsistent internal state
error.
go here java tips weblog
then,put in your project : listtabelmodel.java and rowtablemodel.java add another class with this code:
then drag this class to you jframe,and it's done
it's deprecated,but it works.........
With all factors put into consideration, with regard to code architecture using modular programming would work very well and with more simplicity in the code. Write a simple
pass this funtion to the constructor of the JTabel() constructor i.e
In this case the second argument: columnsArray is a single dimensional array that has the column names
pass the JTable object to a JScrollPane then you are done, right after adding the ScrollPane to the container ofcourse
Here is a sample function getData() that queries the database for the data that later is passed on to the JTable
The JTable constructor accepts two arguments 2dimension Object Array for the data, and String Array for the column names.
eg:
I think this is the Easiest way to populate a table with ResultSet with a method like
And a very simple method can be made as