Search...
FAQs
Subscribe
Pie
FAQs
Recent topics
Flagged topics
Hot topics
Best topics
Search...
Search within JDBC and Relational Databases
Search Coderanch
Advance search
Google search
Register / Login
Post Reply
Bookmark Topic
Watch Topic
New Topic
programming forums
Java
Mobile
Certification
Databases
Caching
Books
Engineering
Micro Controllers
OS
Languages
Paradigms
IDEs
Build Tools
Frameworks
Application Servers
Open Source
This Site
Careers
Other
Pie Elite
all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Campbell Ritchie
Tim Cooke
paul wheaton
Paul Clapham
Ron McLeod
Sheriffs:
Jeanne Boyarsky
Liutauras Vilda
Saloon Keepers:
Tim Holloway
Carey Brown
Roland Mueller
Piet Souris
Bartenders:
Forum:
JDBC and Relational Databases
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
Efekodo Kingsley
Greenhorn
Posts: 6
posted 15 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
need help urgently in identifying the problem with my code.i have table which suppose to retrieve data from database but is giving me an error message.thanks in advance
table class
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package table; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.table.AbstractTableModel; /** * * @author Administrator */ public class AddTableModel extends AbstractTableModel{ private Connection connection; private Statement statement; private ResultSet resultSet; private ResultSetMetaData metaData; private int numberOfRows; // keep track of database connection status private boolean connectedToDatabase = false; public AddTableModel(String driver,String url,String query) throws SQLException,ClassNotFoundException{ try { // load database driver class Class.forName(driver).newInstance(); } catch (InstantiationException ex) { Logger.getLogger(AddTableModel.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(AddTableModel.class.getName()).log(Level.SEVERE, null, ex); } // connect to database connection = DriverManager.getConnection( url); // create Statement to query database statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); // update database connection status connectedToDatabase = true; // set query and execute it setQuery( query ); } public void setNewConnection(String url, String query ) throws SQLException, ClassNotFoundException { // connect to database connection = DriverManager.getConnection( url); // create Statement to query database statement = connection.createStatement( ); // update database connection status connectedToDatabase = true; // set query and execute it setQuery( query ); } // get class that represents column type public Class getColumnClass( int column ) throws IllegalStateException { // ensure database connection is available if ( !connectedToDatabase ) throw new IllegalStateException( "Not Connected to Database" ); // determine Java class of column try { String className = metaData.getColumnClassName( column + 1 ); // return Class object that represents className return Class.forName( className ); } catch ( Exception exception ) { exception.printStackTrace(); } // end catch return Object. class; // if problems occur above, assume type Object } // end method getColumnClass public int getRowCount()throws IllegalStateException { // ensure database connection is available if ( !connectedToDatabase ) throw new IllegalStateException( "Not Connected to Database" ); return numberOfRows; } public int getColumnCount()throws IllegalStateException { // ensure database connection is available if ( !connectedToDatabase ) throw new IllegalStateException( "Not Connected to Database" ); // determine number of columns try { return metaData.getColumnCount(); } // end try catch ( SQLException sqlException ) { sqlException.printStackTrace(); } // end catch return 0; // if problems occur above, return 0 for number of columns } @Override public String getColumnName( int column ) throws IllegalStateException { // ensure database connection is available if ( !connectedToDatabase ) throw new IllegalStateException( "Not Connected to Database" ); // determine column name try { return metaData.getColumnName( column + 1 ); } // end try catch ( SQLException sqlException ) { sqlException.printStackTrace(); } // end catch return ""; // if problems, return empty string for column name } // end method getColumnName public Vector<String> getColumnNames() throws IllegalStateException{ Vector<String> columnnames = new Vector<String>(); if ( !connectedToDatabase ) throw new IllegalStateException( "Not Connected to Database" ); // determine column name try { //String colname = metaData.getColumnName( column + 1 ); int numColumns = metaData.getColumnCount(); // Get the column names; column indices start from 1 for (int i=1; i<numColumns+1; i++) { String columnName = metaData.getColumnName(i); columnnames.addElement(columnName); // Get the name of the column's table name //String tableName = metaData.getTableName(i); } } // end try catch ( SQLException sqlException ) { sqlException.printStackTrace(); } // end catch return columnnames; } public Object getValueAt(int row, int column)throws IllegalStateException { // ensure database connection is available if ( !connectedToDatabase ) throw new IllegalStateException( "Not Connected to Database" ); // obtain a value at specified ResultSet row and column try { resultSet.absolute( row + 1 ); return resultSet.getObject( column + 1 ); } // end try catch ( SQLException sqlException ) { sqlException.printStackTrace(); } // end catch return ""; // if problems, return empty string object } private void setQuery(String query)throws SQLException, IllegalStateException { // ensure database connection is available if ( !connectedToDatabase ) throw new IllegalStateException( "Not Connected to Database" ); // specify query and execute it resultSet = statement.executeQuery(query); // obtain meta data for ResultSet metaData = resultSet.getMetaData(); // determine number of rows in ResultSet resultSet.last(); // move to last row numberOfRows = resultSet.getRow(); // get row number // notify JTable that model has changed fireTableStructureChanged(); } // close Statement and Connection public void disconnectFromDatabase() { if (!connectedToDatabase) return; // close Statement and Connection try { statement.close(); connection.close(); } // end try catch ( SQLException sqlException ) { sqlException.printStackTrace(); } // end catch finally // update database connection status { connectedToDatabase = false; } // end finally } // end method disconnectFromDatabase }
error message
loaded driver and datasource: jdbc:odbc:save java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.String.substring(String.java:1938) at sun.jdbc.odbc.JdbcOdbcResultSet.reWordAsCountQuery(JdbcOdbcResultSet.java:6558) at sun.jdbc.odbc.JdbcOdbcResultSet.calculateRowCount(JdbcOdbcResultSet.java:6351) at sun.jdbc.odbc.JdbcOdbcResultSet.initialize(JdbcOdbcResultSet.java:155) at sun.jdbc.odbc.JdbcOdbcStatement.getResultSet(JdbcOdbcStatement.java:424) at sun.jdbc.odbc.JdbcOdbcStatement.executeQuery(JdbcOdbcStatement.java:254) at table.AddTableModel.setQuery(AddTableModel.java:176) at table.AddTableModel.<init>(AddTableModel.java:48) at table.NewJFrame.initComponents(NewJFrame.java:45) at table.NewJFrame.<init>(NewJFrame.java:22) at table.NewJFrame$2.run(NewJFrame.java:118) at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209) at java.awt.EventQueue.dispatchEvent(EventQueue.java:597) at java.awt.Eve at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161) at java.awt.EventDispatchThread.run(EventDispatchThread.java:122) BUILD SUCCESSFUL (total time: 7 seconds)
class using the table class
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * NewJFrame.java * * Created on Aug 2, 2009, 4:26:55 AM */ package table; /** * * @author Administrator */ public class NewJFrame extends javax.swing.JFrame { /** Creates new form NewJFrame */ public NewJFrame() { initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { scroll = new javax.swing.JScrollPane(); table = new javax.swing.JTable(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setLocationRelativeTo(null); loadDriver(); try{ scroll.getViewport().remove(table); scroll.validate(); tablemodel = new AddTableModel(driver,url,query); table.setModel(tablemodel); scroll.setViewportView(table); scroll.validate(); }catch(Exception e){ e.printStackTrace(); } table.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {}, {}, {} }, new String [] { } )); scroll.setViewportView(table); jButton1.setText("add"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(30, 30, 30) .addComponent(scroll, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(23, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(248, Short.MAX_VALUE) .addComponent(jButton1) .addGap(206, 206, 206)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(scroll, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton1) .addContainerGap(23, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed NewJDialog dialog = new NewJDialog(new javax.swing.JFrame(), true); dialog.setLocationRelativeTo(this); dialog.setVisible(true); }//GEN-LAST:event_jButton1ActionPerformed public void loadDriver(){ try{ Class.forName(driver); System.out.println("loaded driver and datasource: " + url); }catch(Exception ex){ } } /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new NewJFrame().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JScrollPane scroll; private AddTableModel tablemodel; public static javax.swing.JTable table; // End of variables declaration//GEN-END:variables private String driver = "sun.jdbc.odbc.JdbcOdbcDriver"; private String url = "jdbc:odbc:save"; static final String query = "select*from account"; }
Did you see how Paul
cut 87% off of his electric heat bill with 82 watts of micro heaters
?
reply
reply
Bookmark Topic
Watch Topic
New Topic
Boost this thread!
Similar Threads
Bean New class wont compile
Dynamic textfield creation
caculating the difference between dates
Jtable CellEditor
updating database cause error
More...