Error when calling getColumnCount() from ResultSet metadata - java

I seem to be have a problem when trying to get the coulmn count from a resultset's metadata. THe error is Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: SQLite JDBC: inconsistent internal state.
THe idea is to use this table model to populate a JTable with the result from the database query. However when I do I get the above error.
The relevant code is:
public DefaultTableModel buildFlightModel()
throws SQLException {
query="SELECT Airline.AirlineName, Flight.FlightID, Flight.Location, Flight.Destination, Flight.ArriveTime, Flight.LeaveTime FROM Flight INNER JOIN Airline ON Airline.AirlineID=Flight.AirlineID;";
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:coursework.db");
stmt = c.createStatement();
rs=stmt.executeQuery(query);
while(rs.next()){
//System.out.println(s);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ResultSetMetaData metaData = rs.getMetaData();
// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount; column++) {
columnNames.add(metaData.getColumnName(column));
}
// data of the table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}
Any thoughts/ideas/help would be deeply appreciated. Thank you.

This exception is thrown when ResultSet.isclose() == true. Try to create a Clone of the MetaData before starting the Read-Loop.

Related

Refresh JFrame contents DefaultTableModel

I'm trying to figure out how to make a table window update once the model has changed using an example from another site. Everything works but I can't figure how to refresh the window once the table model has changed.
EDIT: I used the suggestion from Bell and re-arranged some things so that the constructor calls my getmodel3 method to populate the table. I thought I could use the setmodel method to change the model and update the table but it isn't working as I thought. Here's what I thought would, but doesn't happen:
The main method creates a new instance of the table using the model passed from the getmodel3 method.
After the table is constructed I call the setmodel method to load different data into a new model using the returned model from getmodel4.
The instance from step 1 is updated with new model data and the new data is shown in the table.
What actually happens is, a new instance is created and uses the model returned from getmodel3, then the setmodel method runs and updates the model variable from a different set of data, but the table doesn't show the change.
public class myTable extends JFrame
{
public volatile DefaultTableModel model = (DefaultTableModel) myTable.getmodel3();
public void setmodel(DefaultTableModel newModel)
{
this.model = newModel;
}
public myTable()
{
JTable table = new JTable( model );
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
JPanel buttonPanel = new JPanel();
getContentPane().add( buttonPanel, BorderLayout.SOUTH );
}
public static void main(String[] args)
{
myTable frame = new myTable();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
frame.setmodel(getmodel4());
}
Here is getmodel3 which is identical to getmodel4 except they point to different database files for different data.
public static DefaultTableModel getmodel3(){
Vector<Object> columnNames = new Vector<Object>();
Vector<Object> data = new Vector<Object>();
try
{
// Connect to an Access Database
String url = "jdbc:sqlite:c:\\sqlite3\\test.db";
Connection conn = DriverManager.getConnection(url);
// Read data from a table
String sql = "Select * from Tasks";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery( sql );
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++)
{
columnNames.addElement( md.getColumnName(i) );
}
// Get row data
while (rs.next())
{
Vector<Object> row = new Vector<Object>(columns);
for (int i = 1; i <= columns; i++)
{
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
rs.close();
stmt.close();
conn.close();
}
catch(Exception e)
{
System.out.println( e );
}
// Create table with database data
DefaultTableModel model = new DefaultTableModel(data, columnNames)
{
#Override
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;
}
};
System.out.println("got model");
return model;
}
You can use existing model by using table.getModel() and set new/existing model using table.setModel(yourModel)
DefaultTableModel model = (DefaultTableModel) table.getModel();
// do modification here
table.setModel(model);
Well, with some of your help I finally figured it out. setModel wasn't working because 1, it wasn't accessible from the scope of the method where I tried to use it, and 2 I tried to make my own setter setmodel but I had no idea what I was doing :).
In the end, I initialized in an easier to reach place so I didn't mess with objects in other methods. Here is the working result that loads a table when main is called and later I can call the update method to reload it. Thanks for the help folks.
public class able extends JFrame
{
//initialize here for easy access. getmodel3() is the model getter method and
//returns the defaultTableModel object
private static able frame = new able();
private static JTable table = new JTable( getmodel3() );
//Start all main stuff here using the previously initialized objects.
public static void main(String[] args)
{
JScrollPane scrollPane = new JScrollPane( table );
frame.getContentPane().add( scrollPane );
JPanel buttonPanel = new JPanel();
frame.getContentPane().add( buttonPanel, BorderLayout.SOUTH );
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
}
public static void update()
{
table.setModel(getmodel3());
}
//This method makes the table model from sql result set and returns it.
//(found online somewhere thanks to whoever wrote it)
public static DefaultTableModel getmodel3(){
Vector<Object> columnNames = new Vector<Object>();
Vector<Object> data = new Vector<Object>();
try
{
// Connect to an Access Database
String url = "jdbc:sqlite:c:\\sqlite3\\test.db";
Connection conn = DriverManager.getConnection(url);
// Read data from a table
String sql = "Select * from Tasks";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery( sql );
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++)
{
columnNames.addElement( md.getColumnName(i) );
}
// Get row data
while (rs.next())
{
Vector<Object> row = new Vector<Object>(columns);
for (int i = 1; i <= columns; i++)
{
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
rs.close();
stmt.close();
conn.close();
}
catch(Exception e)
{
System.out.println( e );
}
// Create table with database data
DefaultTableModel model3 = new DefaultTableModel(data, columnNames)
{
#Override
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;
}
};
System.out.println("got model");
return model3;
}
public static DefaultTableModel getmodel4(){
Vector<Object> columnNames = new Vector<Object>();
Vector<Object> data = new Vector<Object>();
try
{
// Connect to an Access Database
String url = "jdbc:sqlite:c:\\sqlite3\\test2.db";
Connection conn = DriverManager.getConnection(url);
// Read data from a table
String sql = "Select * from Tasks";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery( sql );
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++)
{
columnNames.addElement( md.getColumnName(i) );
}
// Get row data
while (rs.next())
{
Vector<Object> row = new Vector<Object>(columns);
for (int i = 1; i <= columns; i++)
{
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
rs.close();
stmt.close();
conn.close();
}
catch(Exception e)
{
System.out.println( e );
}
// Create table with database data
DefaultTableModel model3 = new DefaultTableModel(data, columnNames)
{
#Override
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;
}
};
System.out.println("got model");
return model3;
}
}

JTable missing first row

i already searched the whole web but I can't find a solution, so i decided to ask here.
Following problem: I am using those 2 methods to populate a JTable with a DefaultTableModel, the ResultSet shows the right amount of data entries (i already searched it with System.out.println) but the JTable always misses the first row
I am using a method to get a ResultSet like this:
public static JTable DBCFillBTableAuftraege() {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
JTable table = null;
try {
con = DriverManager.getConnection(host, uName, uPass);
stmt = con.createStatement( );
rs = stmt.executeQuery("SELECT a.auftrags_nr, k.firma, a.auftragsdatum, a.lieferdatum, a.rechnungsbetrag, k.name, k.strasse, k.plz, k.ort from auftrag a join kunde k on k.kunden_nr = a.kunden_nr ");
while (rs.next()) {
table = new JTable(tableModel(rs));
return table;
}
} catch (SQLException e) {
System.out.println(e);
} finally {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return table;
}
Which then calls this method:
public static DefaultTableModel TableModel(ResultSet rs)
throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
System.out.println(rs);
// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount; column++) {
columnNames.add(metaData.getColumnName(column));
}
// data of the table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}
In my main:
TableAuftrag = DBCFillBTableAuftraege();
scpaneBestell.setViewportView(TableAuftrag);
It works fine, it is showing me my column headers and the data, except one problem:
It is always missing the first row and starts with the second one
Your problem starts here...
// Move to first row...
while (rs.next()) {
table = new JTable(tableModel(rs));
return table;
}
and manifests
// Move to second row and beyond...
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
Basically, in the first while (rs.next()), you move to the first row, but in the second while (rs.next()) you move to the second row, without handling the first...
It might be better to simply pass the ResultSet directly to the TableModel.
Convention would also suggest that you probably should not need to create a new JTable, but instead, just create a new TableModel and apply to a pre-existing table
while (rs.next()) {
table = new JTable(tableModel(rs));
return table;
}
You're consuming the first row of the result set here, and then call tableModel(), which consumes the other rows. The while loop is useless. Just do
table = new JTable(tableModel(rs));
return table;

I need to fix my update to the dynamic jTable by a search in my Access database

I have a problem in updating my single jtable from Microsoft Access Database.
I do not have any error messages. I tried out the Query for the database using like, but my jtable does not populate in relation to the data stored in the database.
public TableModel setAuthorSearchEjournalTableValues(){
String eJournalAuthor = jTextField30.getText();
ResultSet tableData = DCE.searchEjournalbyAuthor(eJournalAuthor);
try {
ResultSetMetaData md = tableData.getMetaData();
int columnCount = md.getColumnCount();
Vector columns = new Vector(columnCount);
for (int i = 1; i <= columnCount; i++) {
columns.add(md.getColumnName(i));
}
Vector data = new Vector();
Vector row;
while (tableData.next()) {
row = new Vector(columnCount);
for (int i = 1; i <= columnCount; i++) {
row.addElement( tableData.getString(i) );
}
data.add(row);
}
DefaultTableModel tableModel = new DefaultTableModel(data, columns);
return tableModel;
//Debugging
} catch (SQLException ex) {
ex.printStackTrace();
}
return null;
}`
And my result retrieving query is here
public ResultSet searchEjournalbyAuthor(String author){
conn = Connect();
try{
String myQuery = "select AuthorDetails,Year,Titleofarticle,Journaltitle,volume,pagenumbers,URL,AccessedDate from Ejournalcitation where AuthorDetails = '"+author+"'";
pst = conn.prepareStatement(myQuery);
rs = pst.executeQuery();
return rs;
}catch(SQLException ex){
ex.printStackTrace();
}
return null;
}
with the code to display as
private void jTextField30KeyReleased(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
if(jComboBox1.getSelectedIndex()==0&&jComboBox2.getSelectedIndex()==0){//BookTitle
jTable1.setModel(setTitleSearchBookTableValues());
}
else if(jComboBox1.getSelectedIndex()==0&&jComboBox2.getSelectedIndex()==1){//BookAuthor
jTable1.setModel(setAuthorSearchBookTableValues());
}
else if(jComboBox1.getSelectedIndex()==1&&jComboBox2.getSelectedIndex()==0){//WebSiteTitle
jTable1.setModel(setTitleSearchWebSiteTableValues());
}
else if(jComboBox1.getSelectedIndex()==1&&jComboBox2.getSelectedIndex()==1){//WebSiteAuthor
jTable1.setModel(setAuthorSearchWebSiteTableValues());
}
else if(jComboBox1.getSelectedIndex()==2&&jComboBox2.getSelectedIndex()==0){//Ejournaltitle
jTable1.setModel(setTitleSearchEjournalTableValues());
}
else if(jComboBox1.getSelectedIndex()==3&&jComboBox2.getSelectedIndex()==1){//EjournalAuthor
jTable1.setModel(setAuthorSearchEjournalTableValues());
}
else{
JOptionPane.showMessageDialog(null, "Please enter a value and select the type of search");
}
}
Help me out!! Thanks in advance
you must include
DefaultTableModel tableModel = (DefaultTableModel) jTable1.getModel();
tableModel.fireTableDataChanged();
with the corrected query
String myQuery = "select AuthorDetails,Year,Titleofarticle,Journaltitle,volume,pagenumbers,URL,AccessedDate from Ejournalcitation where AuthorDetails like '%"+author+"%'";

ResultSet.beforeFirst() gets ignored in Java

I would like to create DefaultTableModel from ResultSet. To do that, I need Object[][].
For that, I have to specify the size of the object before I iterate through the table: I go to the rs.last(), then rs.getRow(), then rs.beforeFirst();
After that, the rs.next() does not executes in the while cycle.
What am I doing wrong?
public static DefaultTableModel buildTableModel(ResultSet _resultSet) {
ResultSetMetaData metaData;
Object[] columnNames = null;
Object[][] tableData = null;
int columnCount;
int currentRowNumber = 0;
try {
metaData = _resultSet.getMetaData();
columnCount = metaData.getColumnCount();
columnNames = new Object[columnCount];
_resultSet.last();
tableData = new Object[_resultSet.getRow()][columnCount];
_resultSet.beforeFirst();
for (int currentColumn = 0; currentColumn <= columnCount; currentColumn++) {
columnNames[currentColumn] = metaData.getColumnName(currentColumn + 1);
}
while (_resultSet.next()) {
for (int columnIndex = 0; columnIndex <= columnCount; columnIndex++) {
tableData[currentRowNumber][columnIndex] = _resultSet.getObject(columnIndex + 1);
}
currentRowNumber++;
}
} catch (SQLException ex) {
System.out.println("bad");
}
return new DefaultTableModel(tableData, columnNames);
}
Probably your ResultSet is not scroll insensitive, that is, it can only be traversed forward.
See the documentation here:
[...] A default ResultSet object is not updatable and has a cursor that moves forward only. Thus, you can iterate through it only once and only from the first row to the last row. [...]
To create a bi-directional one, do something like:
Connection conn = DriverManager.getConnection(...);
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ...);
ResultSet rset = stmt.executeQuery(sql);
At first you need to print column name from ResultSetMetaData. Than you apply _resultSet.last(); and _resultSet.beforeFirst();. This way it has been working my machine.
public static DefaultTableModel buildTableModel(ResultSet _resultSet) {
ResultSetMetaData metaData;
Object[] columnNames = null;
Object[][] tableData = null;
int columnCount;
int currentRowNumber = 0;
try {
metaData = _resultSet.getMetaData();
columnCount = metaData.getColumnCount();
columnNames = new Object[columnCount];
// Print column here.
for (int currentColumn = 0; currentColumn <= columnCount; currentColumn++) {
columnNames[currentColumn] = metaData.getColumnName(currentColumn + 1);
}
tableData = new Object[_resultSet.getRow()][columnCount];
//Here point resultSet cursor to last and beforeFirst.
_resultSet.last();
_resultSet.beforeFirst();
// After swaping the above part. Now it will enter on while loop.
while (_resultSet.next()) {
for (int columnIndex = 0; columnIndex <= columnCount; columnIndex++) {
tableData[currentRowNumber][columnIndex] = _resultSet.getObject(columnIndex + 1);
}
currentRowNumber++;
}
} catch (SQLException ex) {
System.out.println("bad");
}
return new DefaultTableModel(tableData, columnNames);
}

Inserting a resultset into jtable directly

If is there any way to insert a resultset into jtable directly?
Bad idea.
You shouldn't be passing anything from the java.sql package out of your persistence tier.
You can certainly iterate over a ResultSet and load the contents into your DefaultTableModel. But I wouldn't recommend it.
Something like this:
public DefaultTableModel map(ResultSet resultSet) throws SQLException
{
DefaultTableModel defaultTableModel = new DefaultTableModel();
ResultSetMetaData meta = resultSet.getMetaData();
int numberOfColumns = meta.getColumnCount();
while (resultSet.next())
{
Object [] rowData = new Object[numberOfColumns];
for (int i = 0; i < rowData.length; ++i)
{
rowData[i] = resultSet.getObject(i+1);
}
defaultTableModel.addRow(rowData);
}
return defaultTableModel;
}

Categories