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.
You have to Download the Jar called rs2xml by click this link rs2xml.jar Then Add it to your project libraries then import
I prepare Only a method to do so as a sample
Hope this will help more
I think the simplest way to build a model from an instance of
ResultSet
, could be as follows.The method
buildTableModel
:UPDATE
Do you like to use
javax.swing.SwingWorker
? Do you like to use thetry-with-resources
statement?Class
Row
will handle one row from your database.Complete implementation of UpdateTask responsible for filling up UI.
Table Model:
Main Application which builds UI and does the database connection
Well I'm sure that this is the simplest way to populate JTable from ResultSet, without any external library. I have included comments in this method.
I think this is the Easiest way to populate/model a table with ResultSet.. Download and include rs2xml.jar Get rs2xml.jar in your libraries..
This is my approach: