JTable and Postgres Database

Hi there
Is it possible to use JDBC to connect to a postgres database and then display the output in a JTable?
IF anybody can give me some pointers on how to do this...please shout..
any web-sites to look at?

I'll post my db class here:
not a very good one but for a small applet wich doesn't do exciting stuff more the sufficient
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Connection;
* Created on 6-jun-2003
* To change this generated comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
* @author Mr Light
* To change this generated comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
public class DataBase {
     private DatabaseMetaData metaData;
     private Statement statement;
     private Connection connection;
     private String query;
     private ResultSet result;
     public SELECT select;
     public     ALTER alter;
     public CHECK check;
     private interface SELECT {
     private interface ALTER {
     private interface CHECK {
     public void openConnection() {
          try {
               // Initialiseer de PostGreSQL-driver
               Class.forName("org.postgresql.Driver");
               // Syntax: "jdbc:postgresql://host:port/database"
               String url = "jdbc:postgresql://oege.ie.hva.nl:4000/bts51";
               String user = "bts51", pass = "eenenvijftig";
               // Open connectie met database
               connection = DriverManager.getConnection(url, user, pass);
          // Vang JDBC-errors af
          catch( ClassNotFoundException e) {
               System.err.println("JDBC Error:");
               e.printStackTrace();
          // Vang SQL-errors af
          catch (java.sql.SQLException e) {
               System.err.println("SQL Exception:");
               e.printStackTrace();
     // Methode: Sluit connectie met database
     public void closeConnection() {
          try {
               statement.close();
               connection.close();
          catch( Exception e ) {
               // NTS geeft een output null bij statement null
               System.out.println( e.getMessage() );
     // Methode: Voer een Select query uit
     public ResultSet sendQuery(String query, SELECT select) {
          this.query = query;
          try {
               statement = connection.createStatement();
               result = statement.executeQuery(query);
               return result;
          catch (java.sql.SQLException e) {
               System.err.println("SQL Exception:");
               e.printStackTrace();
          return null;
     // Methode: Voer een query uit en geef trug of er hits zijn.
     public boolean sendQuery(String query, CHECK check) {
          try {
               statement = connection.createStatement();
               result = statement.executeQuery(query);
               if (result.next()) {
                    return true;
          catch (java.sql.SQLException e) {
               System.err.println("SQL Exception:");
               e.printStackTrace();
          return false;
     public void sendQuery(String query, ALTER alter) {
          try {
               statement = connection.createStatement();
               result = statement.executeQuery(query);
          catch (java.sql.SQLException e) {
               System.err.println("SQL Exception:");
               e.printStackTrace();
     public void getFunctions() {
          try {
               metaData = connection.getMetaData();
               String SQLKeywords = metaData.getSQLKeywords();
               System.out.println("SQLKeywords: "+SQLKeywords);
               String stringFunctions = metaData.getStringFunctions();
               System.out.println("stringFunctions: "+stringFunctions);
               String systemFunctions = metaData.getSystemFunctions();
               System.out.println("systemFunctions: "+systemFunctions);
               String timeDateFunctions = metaData.getTimeDateFunctions();
               System.out.println("timeDateFunctions: "+timeDateFunctions);
          catch (java.sql.SQLException e) {
               System.err.println("SQL Exception:");
               e.printStackTrace();
}the above to connect
     public Object[][] vestigingen(){
          dataBase.openConnection();
          resultset = dataBase.sendQuery("" +
               "SELECT vestigingscode, vestigingsnaam " +
               "FROM vestiging" +
               "",dataBase.select);
          Object[][] matrix = createMatrix(resultset);
          dataBase.closeConnection();
          return matrix;     
     }there you have the query
plus supporting methode:
private Object[][] createMatrix(ResultSet result) {
          Object[][] matrix = null;
          ResultSetMetaData resultSetMetaData = null;
          try {
               int col = 0;
               int row = 0;
               int totalrows = 0;
               int totalcolums = 0;
               resultSetMetaData = result.getMetaData();
               totalcolums = resultSetMetaData.getColumnCount();
               while(result.next()){
                    totalrows++;
               result.beforeFirst();
               matrix = new Object[totalrows][totalcolums];               
               for(row=0; row < totalrows; row++ ){
                    result.next();
                    if(totalrows == 0){
                         //     geen hits.
                         matrix[col][0] = new String("empty");
                    } else {
                         for(col=0; col < totalcolums; col++ ) {
                              matrix[row][col] = result.getObject(col+1);
          } catch (Exception e) {
               e.printStackTrace();
          return matrix;     
     }then you simply toss the Object[][]
into a JTable
by calling the default constructor.
if that doesn't help you I don't know what will.

Similar Messages

  • Problem with Crystal reports for Eclipse and Postgres-databases

    Hi,
    Is there a known problem when using a PostgreSQL-database to create a report with Crystal reports Plugin? When I drag a table, then occurs a error-windows, that the object can't  created.
    I have found a workaround for solving the problem. After new installing Eclipse Platform Version: 3.4.1 Build id: M20080911-1700 and Crystal reports Plugin 11.8.6.v1371 with JRE 1.6.0_01 the error message allways occurs, when I select a table from a PostgreSQL database (Version 8.2). After restarting eclipse you see the last selected tables in the field explorer and you can drag the table fields in the report. A repeated choice of the same table causes aliases for the table in the field explorer after restarting eclipse.
    Error.log:
    eclipse.buildId=M20080911-1700
    java.version=1.6.0_01
    java.vendor=Sun Microsystems Inc.
    BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=de_DE Command-line arguments:  -os win32 -ws win32 -arch x86
    Error
    Tue Dec 16 14:03:53 CET 2008
    Verursacht durch: java.lang.IllegalArgumentException
    com.businessobjects.crystalreports.designer.core.ReportException: java.lang.IllegalArgumentException
    at com.businessobjects.crystalreports.designer.core.ExceptionFactory.B(Unknown Source) at com.businessobjects.crystalreports.designer.core.ExceptionFactory.create(Unknown Source) at com.businessobjects.crystalreports.designer.core.elements.data.TableElement.add(Unknown Source) at com.businessobjects.crystalreports.designer.core.commands.AddCommand.doCommand(Unknown Source) at com.businessobjects.crystalreports.designer.core.commands.ReportCommand.C(Unknown Source) at com.businessobjects.crystalreports.designer.core.commands.ReportCommand.execute(Unknown Source) at com.businessobjects.crystalreports.designer.CoreCommand.execute(Unknown Source) at com.businessobjects.crystalreports.designer.dseintegration.DSEDropHandler.drop(Unknown Source) at org.eclipse.jface.util.DelegatingDropAdapter$3.run(DelegatingDropAdapter.java:211)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:37)
    at org.eclipse.core.runtime.Platform.run(Platform.java:880)
    at org.eclipse.ui.internal.JFaceUtil$1.run(JFaceUtil.java:48)
    at org.eclipse.jface.util.SafeRunnable.run(SafeRunnable.java:175)
    at org.eclipse.jface.util.DelegatingDropAdapter.drop(DelegatingDropAdapter.java:209)
    at org.eclipse.swt.dnd.DNDListener.handleEvent(DNDListener.java:90)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1003)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1027)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1012)
    at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:770)
    at org.eclipse.swt.dnd.DropTarget.Drop(DropTarget.java:455)
    at org.eclipse.swt.dnd.DropTarget$3.method6(DropTarget.java:257)
    at org.eclipse.swt.internal.ole.win32.COMObject.callback6(COMObject.java:119)
    at org.eclipse.swt.internal.ole.win32.COM.DoDragDrop(Native Method) at org.eclipse.swt.dnd.DragSource.drag(DragSource.java:362)
    at org.eclipse.swt.dnd.DragSource.access$0(DragSource.java:288)
    at org.eclipse.swt.dnd.DragSource$1.handleEvent(DragSource.java:171)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1003)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3823)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3422)
    at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2382)
    at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2346)
    at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2198)
    at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:493)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:288)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:488)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:113)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:193)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:386)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:549)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:504)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1236)
    Caused by: com.crystaldecisions.sdk.occa.report.lib.ReportSDKException: java.lang.IllegalArgumentException---- Error code:-2147467259 Error code name:failed at com.businessobjects.reports.sdk.JRCCommunicationAdapter.request(Unknown Source) at com.crystaldecisions.proxy.remoteagent.x.a(Unknown Source) at com.crystaldecisions.proxy.remoteagent.q.a(Unknown Source) at com.crystaldecisions.sdk.occa.report.application.dd.a(Unknown Source) at com.crystaldecisions.sdk.occa.report.application.ag.a(Unknown Source) at com.crystaldecisions.sdk.occa.report.application.bu.if(Unknown Source) at com.crystaldecisions.sdk.occa.report.application.bu.void(Unknown Source) at com.crystaldecisions.sdk.occa.report.application.a6.for(Unknown Source) at com.crystaldecisions.proxy.remoteagent.u.performDo(Unknown Source)
    Best Regards
    Arnold

    Your issue appears to be a Crystal Reports for Eclipse report designer thing, and not a JRC runtime thing.  The JRC runtime does support Type 4 JDBC drivers, but all modern PostgreSQL drivers are Type 4.
    The current report designer is more restrictive than the JRC runtime - and PostgreSQL, being not on the supported platforms list, has never been tested with the embedded designer.
    Unless there's anybody out there with experience with PostgreSQL and CR4E designer, who would be willing to share their experiences.
    Sincerely,
    Ted Ueda

  • How to use JTable and database

    how i want to know how to store data into Jtable from the database for the end users.
    any tutorial or example will be helpfull.
    thank you

    my problem is i want to store data that i will get from the database into a JTableThen you problem is with Swing in which case you should be searching the Swing forum for answers. This question has been asked and answered several times. I know I've posted solutions before.

  • Jtable and database

    hi,
    i am using jdevlopper 10g and oracle 10g express.
    i create a database and a new connection to it.
    in the first frame, i created a new jtable and i want that it containts data from the database.
    is any one can help me.
    thanks

    Hi,
    you have two options:
    - Use ADF and ADF Swing, in which cae the database connect is through a business service (e.g. ADF Business Components or EJB)
    - Create a JDBC connection to the database and populate the JTable model with the data (which is cumbersome). You find tutorials on the web of how to do this.
    Frank

  • JTable and Databases

    Hi all,
    I have two files excerpts from my Java application. I feel that in order for me to get understood so well, with regards to a problem that challenged me, I had to post these two files as you can see below. They are called ResultSetTableModel.java and DisplayQueryResults.java [which gets displayed in an internal frame].
    I have this code from ResultSetTableModel
    // ResultSetTableModel.java
    // A TableModel that supplies ResultSet data to a JTable.
    import java.sql.Connection;
    import java.sql.Statement;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import javax.swing.table.AbstractTableModel;
    // ResultSet rows and columns are counted from 1 and JTable
    // rows and columns are counted from 0. When processing
    // ResultSet rows or columns for use in a JTable, it is
    // necessary to add 1 to the row or column number to manipulate
    // the appropriate ResultSet column (i.e., JTable column 0 is
    // ResultSet column 1 and JTable row 0 is ResultSet row 1).
    public class ResultSetTableModel 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;
       // constructor initializes resultSet and obtains its meta data object;
       // determines number of rows
       public ResultSetTableModel(String driver, String url,
          String username, String password, String query)
          throws SQLException, ClassNotFoundException {        
          // load database driver class
          Class.forName(driver);
          // connect to database
          connection = DriverManager.getConnection(url, username, password);
          // 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);
       } // end constructor ResultSetTableModel
       // 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);
          } // end try
          catch (Exception exception) {
             exception.printStackTrace();
          } // end catch
          //return Object.class; // if problems occur above, assume type Object
          return getValueAt(0, column).getClass(); // added January 25, 2008 in stead of the one above
       } // end method getColumnClass
       // get number of columns in ResultSet
       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
       } // end method getColumnCount
       // get name of a particular column in ResultSet
       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
       // return number of rows in ResultSet
       public int getRowCount() throws IllegalStateException {     
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          return numberOfRows;
       } // end method getRowCount
       // obtain value in particular row and column
       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
       } // end method getValueAt
        * Don't need to implement this method unless your table's
        * editable.
      public boolean isCellEditable(int row, int column) { // Added on January 25, 2008 6:51 A.M.
         //Note that the data/cell address is constant,
         //no matter where the cell appears onscreen.
         if (column < 2) {
            return false;
         } else {
            return true;
       // set new database query string
       public 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();
       } // end method setQuery
       // 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         
    }  // end class ResultSetTableModelThe DisplayQueryResults code follows:
    // DisplayQueryResults.java
    // Display the contents of the Authors table in the
    // Books database.
    import java.awt.BorderLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.sql.SQLException;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.ScrollPaneConstants;
    import javax.swing.JTable;
    import javax.swing.JOptionPane;
    import javax.swing.JButton;
    import javax.swing.Box;
    import javax.swing.JInternalFrame;
    import java.util.*; // for the Bundle
    import javax.swing.event.InternalFrameEvent;
    import javax.swing.event.InternalFrameListener;
    import javax.swing.event.InternalFrameAdapter;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import javax.swing.event.*; // step 1
    import javax.swing.table.TableModel; // step 1
    public class DisplayQueryResults extends JInternalFrame implements TableModelListener { // step 2
       // JDBC driver, database URL, username and password
       ResourceBundle bundle = ResourceBundle.getBundle("Accounting");
       String JDBC_DRIVER = bundle.getString("Driver");
       String DATABASE_URL = bundle.getString("URL");
       String USERNAME = bundle.getString("User");
       String PASSWORD = bundle.getString("Password");
       String DEFAULT_QUERY = bundle.getString("Query");
       private ResultSetTableModel tableModel;
       private JTextArea queryArea;
       static final int xOffset = 0, yOffset = 200;
       // create ResultSetTableModel and GUI
       public DisplayQueryResults() {  
          super("Sales of the Day",
                  true, //resizable
                  true, //closable
                  true, //maximizable
                  false);//iconifiable
          //...Create the GUI and put it in the window...
          //Set the window's location.
          setLocation(xOffset, yOffset);
          // create ResultSetTableModel and display database table
          try {
             // create TableModel for results of query SELECT * FROM authors
             tableModel = new ResultSetTableModel(JDBC_DRIVER, DATABASE_URL,
                USERNAME, PASSWORD, DEFAULT_QUERY);
             // set up JTextArea in which user types queries
             queryArea = new JTextArea(DEFAULT_QUERY, 1, 100);
             queryArea.setWrapStyleWord(true);
             queryArea.setLineWrap(true);
             JScrollPane scrollPane = new JScrollPane(queryArea,
                ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
             // set up JButton for submitting queries
             JButton submitButton = new JButton("Submit Query");
             // create Box to manage placement of queryArea and
             // submitButton in GUI
             Box box = Box.createHorizontalBox();
             box.add(scrollPane);
             box.add(submitButton);
             // create JTable delegate for tableModel
             final JTable resultTable = new JTable(tableModel);
             resultTable.setFillsViewportHeight(true); // Makes the empty space heights white
             resultTable.setRowSelectionAllowed(true);
             resultTable.getModel().addTableModelListener(this); // step 3
             // place GUI components on content pane
             add(box, BorderLayout.NORTH);
             add(new JScrollPane(resultTable), BorderLayout.CENTER);
             // create event listener for submitButton
             submitButton.addActionListener(
                new ActionListener()
                   // pass query to table model
                   public void actionPerformed(ActionEvent event)
                      // perform a new query
                      try
                         tableModel.setQuery(queryArea.getText());
                      } // end try
                      catch ( SQLException sqlException)
                         JOptionPane.showMessageDialog(null,
                            sqlException.getMessage(), "Database error",
                            JOptionPane.ERROR_MESSAGE);
                         // try to recover from invalid user query
                         // by executing default query
                         try {
                            tableModel.setQuery(DEFAULT_QUERY);
                            queryArea.setText(DEFAULT_QUERY);
                         } // end try
                         catch (SQLException sqlException2) {
                            JOptionPane.showMessageDialog(null,
                               sqlException2.getMessage(), "Database error",
                               JOptionPane.ERROR_MESSAGE);
                            // ensure database connection is closed
                            tableModel.disconnectFromDatabase();
                            System.exit(1); // terminate application
                         } // end inner catch                  
                      } // end outer catch
                   } // end actionPerformed
                }  // end ActionListener inner class         
             ); // end call to addActionListener
             //...Then set the window size or call pack...
                setSize(750,300);
             setVisible(true); // display window 
          } // end try
          catch (ClassNotFoundException classNotFound) {
             JOptionPane.showMessageDialog(null,
                "MySQL driver not found", "Driver not found",
                JOptionPane.ERROR_MESSAGE);
             System.exit(1); // terminate application
          } // end catch
          catch (SQLException sqlException) {
             JOptionPane.showMessageDialog(null, sqlException.getMessage(),
                "Database error", JOptionPane.ERROR_MESSAGE);
             // ensure database connection is closed
             tableModel.disconnectFromDatabase();
             System.exit(1);   // terminate application
          } // end catch
          // dispose of window when user quits application (this overrides
          // the default of HIDE_ON_CLOSE)
          setDefaultCloseOperation(DISPOSE_ON_CLOSE);
          // ensure database connection is closed when user quits application
          addInternalFrameListener(
             new InternalFrameAdapter() {
                // disconnect from database and exit when window has closed
                public void windowClosed(WindowEvent event) {
                   tableModel.disconnectFromDatabase();
                   System.exit(0);
                } // end method windowClosed
             } // end WindowAdapter inner class
          ); // end call to addWindowListener
       } // end DisplayQueryResults constructor
       public void tableChanged(TableModelEvent e) { // step 4
            int row = e.getFirstRow();
            int column = e.getColumn();
            TableModel model = (TableModel)e.getSource();
            String columnName = model.getColumnName(column);
            Object tableModel = model.getValueAt(row, column);
            // Do something with the data...
            System.out.println(tableModel);
            System.out.println("data");
       // execute application
       public static void main(String args[]) {
          new DisplayQueryResults();    
       } // end main
    } // end class DisplayQueryResultsMy problem:
    is in these lines:
    public void tableChanged(TableModelEvent e) { // step 4
            int row = e.getFirstRow();
            int column = e.getColumn();
            TableModel model = (TableModel)e.getSource();
            String columnName = model.getColumnName(column);
            Object tableModel = model.getValueAt(row, column);
            // Do something with the data...
            System.out.println(tableModel);
            System.out.println("data"); // should output in the console
        }How do we notify java that a cell on a row has changed so that we can reflect the changes to the database. The current application shows that the data in cells are editable, but when we edit a cell and hit enter, data changes back to the previous data in that particular cell. And the data as well does not change its state: for example, if a data in the table has a value of boolean value false [checkbox unchecked], I can not modify the checkbox state to checked state. The tableChanged method does not get executed, and therefore, this is a serious error that I cant figure out.
    My question:
    What code should I write so that I will be able to notify java of the changed cell and how do we write the code that will reflect the changed values in a cell into the database?
    Edited by: Oliverbob on Jan 26, 2008 8:40 PM

    This maybe what you're looking for??
    http://developer.java.sun.com/developer/Books/swing2/chapter18-09.html

  • JTable and Database communication

    Hi all,
    I have two files excerpts from my Java application. I feel that in order for me to get understood so well, with regards to a problem that challenged me, I had to post these two files as you can see below. They are called ResultSetTableModel.java and DisplayQueryResults.java [which gets displayed in an internal frame].
    I have this code from ResultSetTableModel
    // ResultSetTableModel.java
    // A TableModel that supplies ResultSet data to a JTable.
    import java.sql.Connection;
    import java.sql.Statement;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import javax.swing.table.AbstractTableModel;
    // ResultSet rows and columns are counted from 1 and JTable
    // rows and columns are counted from 0. When processing
    // ResultSet rows or columns for use in a JTable, it is
    // necessary to add 1 to the row or column number to manipulate
    // the appropriate ResultSet column (i.e., JTable column 0 is
    // ResultSet column 1 and JTable row 0 is ResultSet row 1).
    public class ResultSetTableModel 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;
       // constructor initializes resultSet and obtains its meta data object;
       // determines number of rows
       public ResultSetTableModel(String driver, String url,
          String username, String password, String query)
          throws SQLException, ClassNotFoundException {        
          // load database driver class
          Class.forName(driver);
          // connect to database
          connection = DriverManager.getConnection(url, username, password);
          // 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);
       } // end constructor ResultSetTableModel
       // 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);
          } // end try
          catch (Exception exception) {
             exception.printStackTrace();
          } // end catch
          //return Object.class; // if problems occur above, assume type Object
          return getValueAt(0, column).getClass(); // added January 25, 2008 in stead of the one above
       } // end method getColumnClass
       // get number of columns in ResultSet
       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
       } // end method getColumnCount
       // get name of a particular column in ResultSet
       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
       // return number of rows in ResultSet
       public int getRowCount() throws IllegalStateException {     
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          return numberOfRows;
       } // end method getRowCount
       // obtain value in particular row and column
       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
       } // end method getValueAt
        * Don't need to implement this method unless your table's
        * editable.
      public boolean isCellEditable(int row, int column) { // Added on January 25, 2008 6:51 A.M.
         //Note that the data/cell address is constant,
         //no matter where the cell appears onscreen.
         if (column < 2) {
            return false;
         } else {
            return true;
       // set new database query string
       public 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();
       } // end method setQuery
       // 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         
    }  // end class ResultSetTableModelThe DisplayQueryResults code follows:
    // DisplayQueryResults.java
    // Display the contents of the Authors table in the
    // Books database.
    import java.awt.BorderLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.sql.SQLException;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.ScrollPaneConstants;
    import javax.swing.JTable;
    import javax.swing.JOptionPane;
    import javax.swing.JButton;
    import javax.swing.Box;
    import javax.swing.JInternalFrame;
    import java.util.*; // for the Bundle
    import javax.swing.event.InternalFrameEvent;
    import javax.swing.event.InternalFrameListener;
    import javax.swing.event.InternalFrameAdapter;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import javax.swing.event.*; // step 1
    import javax.swing.table.TableModel; // step 1
    public class DisplayQueryResults extends JInternalFrame implements TableModelListener { // step 2
       // JDBC driver, database URL, username and password
       ResourceBundle bundle = ResourceBundle.getBundle("Accounting");
       String JDBC_DRIVER = bundle.getString("Driver");
       String DATABASE_URL = bundle.getString("URL");
       String USERNAME = bundle.getString("User");
       String PASSWORD = bundle.getString("Password");
       String DEFAULT_QUERY = bundle.getString("Query");
       private ResultSetTableModel tableModel;
       private JTextArea queryArea;
       static final int xOffset = 0, yOffset = 200;
       // create ResultSetTableModel and GUI
       public DisplayQueryResults() {  
          super("Sales of the Day",
                  true, //resizable
                  true, //closable
                  true, //maximizable
                  false);//iconifiable
          //...Create the GUI and put it in the window...
          //Set the window's location.
          setLocation(xOffset, yOffset);
          // create ResultSetTableModel and display database table
          try {
             // create TableModel for results of query SELECT * FROM authors
             tableModel = new ResultSetTableModel(JDBC_DRIVER, DATABASE_URL,
                USERNAME, PASSWORD, DEFAULT_QUERY);
             // set up JTextArea in which user types queries
             queryArea = new JTextArea(DEFAULT_QUERY, 1, 100);
             queryArea.setWrapStyleWord(true);
             queryArea.setLineWrap(true);
             JScrollPane scrollPane = new JScrollPane(queryArea,
                ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
             // set up JButton for submitting queries
             JButton submitButton = new JButton("Submit Query");
             // create Box to manage placement of queryArea and
             // submitButton in GUI
             Box box = Box.createHorizontalBox();
             box.add(scrollPane);
             box.add(submitButton);
             // create JTable delegate for tableModel
             final JTable resultTable = new JTable(tableModel);
             resultTable.setFillsViewportHeight(true); // Makes the empty space heights white
             resultTable.setRowSelectionAllowed(true);
             resultTable.getModel().addTableModelListener(this); // step 3
             // place GUI components on content pane
             add(box, BorderLayout.NORTH);
             add(new JScrollPane(resultTable), BorderLayout.CENTER);
             // create event listener for submitButton
             submitButton.addActionListener(
                new ActionListener()
                   // pass query to table model
                   public void actionPerformed(ActionEvent event)
                      // perform a new query
                      try
                         tableModel.setQuery(queryArea.getText());
                      } // end try
                      catch ( SQLException sqlException)
                         JOptionPane.showMessageDialog(null,
                            sqlException.getMessage(), "Database error",
                            JOptionPane.ERROR_MESSAGE);
                         // try to recover from invalid user query
                         // by executing default query
                         try {
                            tableModel.setQuery(DEFAULT_QUERY);
                            queryArea.setText(DEFAULT_QUERY);
                         } // end try
                         catch (SQLException sqlException2) {
                            JOptionPane.showMessageDialog(null,
                               sqlException2.getMessage(), "Database error",
                               JOptionPane.ERROR_MESSAGE);
                            // ensure database connection is closed
                            tableModel.disconnectFromDatabase();
                            System.exit(1); // terminate application
                         } // end inner catch                  
                      } // end outer catch
                   } // end actionPerformed
                }  // end ActionListener inner class         
             ); // end call to addActionListener
             //...Then set the window size or call pack...
                setSize(750,300);
             setVisible(true); // display window 
          } // end try
          catch (ClassNotFoundException classNotFound) {
             JOptionPane.showMessageDialog(null,
                "MySQL driver not found", "Driver not found",
                JOptionPane.ERROR_MESSAGE);
             System.exit(1); // terminate application
          } // end catch
          catch (SQLException sqlException) {
             JOptionPane.showMessageDialog(null, sqlException.getMessage(),
                "Database error", JOptionPane.ERROR_MESSAGE);
             // ensure database connection is closed
             tableModel.disconnectFromDatabase();
             System.exit(1);   // terminate application
          } // end catch
          // dispose of window when user quits application (this overrides
          // the default of HIDE_ON_CLOSE)
          setDefaultCloseOperation(DISPOSE_ON_CLOSE);
          // ensure database connection is closed when user quits application
          addInternalFrameListener(
             new InternalFrameAdapter() {
                // disconnect from database and exit when window has closed
                public void windowClosed(WindowEvent event) {
                   tableModel.disconnectFromDatabase();
                   System.exit(0);
                } // end method windowClosed
             } // end WindowAdapter inner class
          ); // end call to addWindowListener
       } // end DisplayQueryResults constructor
       public void tableChanged(TableModelEvent e) { // step 4
            int row = e.getFirstRow();
            int column = e.getColumn();
            TableModel model = (TableModel)e.getSource();
            String columnName = model.getColumnName(column);
            Object tableModel = model.getValueAt(row, column);
            // Do something with the data...
            System.out.println(tableModel);
            System.out.println("data");
       // execute application
       public static void main(String args[]) {
          new DisplayQueryResults();    
       } // end main
    } // end class DisplayQueryResultsMy problem:
    is in these lines:
    public void tableChanged(TableModelEvent e) { // step 4
            int row = e.getFirstRow();
            int column = e.getColumn();
            TableModel model = (TableModel)e.getSource();
            String columnName = model.getColumnName(column);
            Object tableModel = model.getValueAt(row, column);
            // Do something with the data...
            System.out.println(tableModel);
            System.out.println("data"); // should output in the console
        }How do we notify java that a cell on a row has changed so that we can reflect the changes to the database. The current application shows that the data in cells are editable, but when we edit a cell and hit enter, data changes back to the previous data in that particular cell. And the data as well does not change its state: for example, if a data in the table has a value of boolean value false [checkbox unchecked], I can not modify the checkbox state to checked state. The tableChanged method does not get executed, and therefore, this is a serious error that I cant figure out.
    My question:
    What code should I write so that I will be able to notify java of the changed cell and how do we write the code that will reflect the changed values in a cell into the database?
    Edited by: Oliverbob on Jan 26, 2008 9:54 PM

    Why don't you check out the link shown below:
    http://www.aokabc.com
    and just follow the white rabbit!
    ;o)
    V.V.

  • JTable and ResultSet TableModel with big resultset

    Hi, I have a question about JTable and a ResultSet TableModel.
    I have to develop a swing JTable application that gets the data from a ResultSetTableModel where the user can update the jtable data.
    The problem is the following:
    the JTable have to contain the whole data of the source database table. Currently I have defined a
    a TYPE_SCROLL_SENSITIVE & CONCUR_UPDATABLE statement.
    The problem is that when I execute the query the whole ResultSet is "downloaded" on the client side application (my jtable) and I could receive (with big resultsets) an "out of memory error"...
    I have investigate about the possibility of load (in the client side) only a small subset of the resultset but with no luck. In the maling lists I see that the only way to load the resultset incrementally is to define a forward only resultset with autocommit off, and using setFetchSize(...). But this solution doesn't solve my problem because if the user scrolls the entire table, the whole resultset will be downloaded...
    In my opinion, there is only one solution:
    - create a small JTable "cache structure" and update the structure with "remote calls" to the server ...
    in other words I have to define on the server side a "servlet environment" that queries the database, creates the resultset and gives to the jtable only the data subsets that it needs... (alternatively I could define an RMI client/server distribuited applications...)
    This is my solution, somebody can help me?
    Are there others solutions for my problem?
    Thanks in advance,
    Stefano

    The database table currently is about 80000 rows but the next year will be 200000 and so on ...
    I know that excel has this limit but my JTable have to display more data than a simple excel work sheet.
    I explain in more detail my solution:
    whith a distribuited TableModel the whole tablemodel data are on the server side and not on the client (jtable).
    The local JTable TableModel gets the values from a local (limited, 1000rows for example) structure, and when the user scroll up and down the jtable the TableModel updates this structure...
    For example: initially the local JTable structure contains the rows from 0 to 1000;
    the user scroll down, when the cell 800 (for example) have to be displayed the method:
    getValueAt(800,...)
    is called.
    This method will update the table structure. Now, for example, the table structure will contain data for example from row 500 to row 1500 (the data from 0 to 499 are deleted)
    In this way the local table model dimension will be indipendent from the real database table dimension ...
    I hope that my solution is more clear now...
    under these conditions the only solutions that can work have to implement a local tablemodel with limited dimension...
    Another solution without servlet and rmi that I have found is the following:
    update the local limited tablemodel structure quering the database server with select .... limit ... offset
    but, the select ... limit ... offset is very dangerous when the offset is high because the database server have to do a sequential scan of all previuous records ...
    with servlet (or RMI) solution instead, the entire resultset is on the server and I have only to request the data from the current resultset from row N to row N+1000 without no queries...
    Thanks

  • How to connect JTable to a database to show it?

    al salamo 3alaykom w ra7mato allahe w barakato....
    I tried a lot to connect a JTable to a database to show it.....but i couldnt......
    in the clas where i create it i wrote this code
    Class General extends JFrame{
    // private declaration like:
    private Vector heading = new Vector();
    private Vector data= new Vector();
    private JScrollPane jScrollPane1 = new JScrollPane();
    private JTable jTable1 = new JTable(data,heading);
    public General() {
    try {
    jbInit();
    } catch (Exception e) {
    e.printStackTrace();
    private void jbInit() throws Exception {
    try{
    Connection conc;
    DriverManager.registerDriver((Driver)Class.forName("com.mysql.jdbc.Driver").newInstance());
    conc = DriverManager.getConnection("jdbc:mysql://localhost/tdiary?user=root&useUnicode=true&characterEncoding=utf8");
    Statement stmt = conc.createStatement();
    ResultSet rs= stmt.executeQuery("SELECT * FROM diary");
    String n1 = new String();
    String add = new String();
    String tele1 = new String();
    String tele2 = new String();
    String tele3 = new String();
    String tele4 = new String();
    String mobi1 = new String();
    String mobi2 = new String();
    String mobi3 = new String();
    String mobi4 = new String();
    String mail1 = new String();
    String Details = new String();
    while(rs.next())
    n1 = rs.getString("Name");
    add = rs.getString("Address");
    tele1 = rs.getString("Tel1");
    tele2 = rs.getString("Tel2");
    tele3 = rs.getString("Tel3");
    tele4 = rs.getString("Tel4");
    mobi1 = rs.getString("Mob1");
    mobi2 = rs.getString("Mob2");
    mobi3 = rs.getString("Mob3");
    mobi4 = rs.getString("Mob4");
    mail1 = rs.getString("Mail");
    Details = rs.getString("Details");
    heading.addElement("name");
    heading.addElement("Tel");
    heading.addElement("Mobile");
    heading.addElement("Address");
    heading.addElement("E-mail");
    data.addElement(n1);
    data.addElement(tele1);
    data.addElement(mobi1);
    data.addElement(add);
    data.addElement(mail1);
    System.out.println(data);
    } catch (Exception k){
    k.printStackTrace();
    //and then i continued the code ......
    //but the table doesnt appear....why?....and if there is another way to do it...plz tell me
    i hope someone could help me coz i got mad from this problem.
    thanx
    al salamo 3alaykom w ra7mato allahe w barakato

    Hi,
    Please use code formatting when you post code. See the formattings tips:
    http://forum.java.sun.com/help.jspa?sec=formatting
    I can't see that you have added your table or scroll pane to any content pane. That's why it isn't displayed.
    Kaj
    Ps.
    You have lots of assignements of Strings when you are declaring your variables, it's useless, just set them to null.

  • Which is better:search JTables or search Database tables?

    greetings all
    i have UI With many jtables,every jtable reads data from it's own table in a MySQL database
    and i want to make a search mechanism in a specific column in all the tables
    and once item is found the row is highlighted.
    i made it with two ways:
    1-make for loop in each jtable and once item is found , current loop is exited and other loops are not entered
    2-make connection with the database
    and create several resultsets ,every resultset execute a select query on the desired item
    and if one of the Resultsets returns data means item is found then i highlight it in the equivalent jtable.
    i executed the two ways and felt no difference in the speed of finding item
    but i want to know what is the best way of them or in general,as better design or in case of large applications?
    thanks in advance

    first_knight, you have no bloody idea what you're doing.
    you're asking if it's better to search on the client or the server.
    this suggests to me that the entire contents of the database are brought down to the client. this is usually a bad idea except for very small data sets. in that case, it doesn't matter where you do it.
    if you have lots of data, it's best to let the database do it. first, it will actually have all the data. second, it's been optimized to do searches faster than any code you'll ever write.
    either way, judging from your questions here you'll never get either one to work.
    %

  • Heterogeneous connection between Oracle and Postgres.

    Hi All,
    I'm trying to make an heterogeneous connection between Oracle and Postgres since few days but i still having this error : "lost RPC connection".
    First of all : I'm using Windows 7, Oracle 10g and PostgreSQL 8.4.
    I have done the following operations :
    1) Create a System DNS named "PG". (Test connection is OK)
    2) Create the file "initPG.ora" in "$ORACLE_HOME/hs/admin" :
    # This is a sample agent init file that contains the HS parameters that are
    # needed for an ODBC Agent.
    # HS init parameters
    HS_FDS_CONNECT_INFO = PG
    HS_FDS_TRACE_LEVEL = ON
    # Environment variables required for the non-Oracle system
    #set <envvar>=<value>
    3) Configure the file "listener.ora" (in "$ORACLE_HOME/NETWORK/ADMIN") :
    SID_LIST_LISTENER =
    (SID_LIST =
         (SID_DESC =
    (SID_NAME = PLSExtProc)
    (ORACLE_HOME = C:\oraclexe\app\oracle\product\10.2.0\server)
    (PROGRAM = extproc)
    (SID_DESC =
    (SID_NAME = CLRExtProc)
    (ORACLE_HOME = C:\oraclexe\app\oracle\product\10.2.0\server)
    (PROGRAM = extproc)
         (SID_DESC =
    (SID_NAME = PG)
    (ORACLE_HOME = C:\oraclexe\app\oracle\product\10.2.0\server)
    (PROGRAM = hsodbc)
    LISTENER =
    (DESCRIPTION_LIST =
    (DESCRIPTION =
         (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC_FOR_XE))
    (ADDRESS = (PROTOCOL = TCP)(HOST = Cédric-PC)(PORT = 1521))
    DEFAULT_SERVICE_LISTENER = (XE)
    4) Configure the file "tnsnames.ora" (in "$ORACLE_HOME/NETWORK/ADMIN") :
    XE =
    (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = Cédric-PC)(PORT = 1521))
    (CONNECT_DATA =
    (SERVER = DEDICATED)
    (SERVICE_NAME = XE)
    PG =
    (DESCRIPTION =
    (ADDRESS = (PROTOCOL = tcp)(HOST = Cédric-PC)(PORT = 1521))
    (CONNECT_DATA =
    (SERVICE_NAME = PG)
    (HS = OK)
    EXTPROC_CONNECTION_DATA =
    (DESCRIPTION =
    (ADDRESS_LIST =
    (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC_FOR_XE))
    (CONNECT_DATA =
    (SID = PLSExtProc)
    (PRESENTATION = RO)
    ORACLR_CONNECTION_DATA =
    (DESCRIPTION =
    (ADDRESS_LIST =
    (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC_FOR_XE))
    (CONNECT_DATA =
    (SID = CLRExtProc)
    (PRESENTATION = RO)
    5) Finally, i create my DB-Link and test it :
    CREATE DATABASE LINK "CENTRALE_POSTGRES" CONNECT TO "user_login" IDENTIFIED BY "user_password" USING 'PG';
    SELECT * FROM "dual"@CENTRALE_POSTGRES;
    I got this error :
    ORA-03135 : lost RPC connection.
    As you can see, i have activated the trace level (HS_FDS_TRACE_LEVEL = ON), but the directory "$ORACLE_HOME/NETWORK/trace" still empty.
    Any ideas ?
    Regards

    the tnsnames.ora alias PG is wrong - you need to have 2 closing brackets after the SERVICE_NAME so that HS=OK is outside of the CONNECT_DATA like:
    PG =
    <space>(DESCRIPTION =
    <space><space>(ADDRESS = (PROTOCOL = tcp)(HOST = Cédric-PC)(PORT = 1521))
    <space><space>(CONNECT_DATA =
    <space><space><space>(SERVICE_NAME = PG))
    <space><space>(HS = OK)
    <space>)
    Please be also aware HSODBC up to release 10.2 has been desupported since March 2008 and it was replaced by its follow up product DG4ODBC V11

  • Problem with using Postgres database in java.

    Hi ,
    I am using netbean netbean IDE 6.1.5 and postgres as my database.
    I want to pass a date to a query in java like-
    "select count(\"JOBID\") from emp
    to_char(\"STARTTIME\",'yyyy-MM-dd')=" + datestr
    where STARTTIME is a date field,
    but when I run the program it gives the error
    error: operator does not exist: text = integer
    even if I use this query
    ResultSet result1= stmt.executeQuery("select count(\"JOBID\") frrom emp "+
    " where to_date(\"STARTTIME\",'YYYY-MM-DD HH:MI:SS')=" + sqlDate);
    WHERE STARTDATE is string and
    sqlDate=java.sql.Date sqlDate
    it gives
    error:error: operator does not exist: date = integer
    please help
    moni

    Use PreparedStatement instead of Statement all the way. Not only it is faster and saves you from any SQL injection risks, but it also eases setting complex Java objects in a SQL query. It has for example a setDate() method.
    Prepare here: [http://java.sun.com/docs/books/tutorial/jdbc/basics/prepared.html].

  • Giving input to jtable from a database in runtime

    friends
    previously i have posted an query asking how to intilize the row size of jtable in run time for which i got good rewsponce to direct me to an page in sun/components,i read the jtable page in specifie link provided in sun,but i could not figure out how to give input to jtable from a database on runtime.In that page they have used by giving input in an array and then displaying it, by that they set the no of rows in the table ,but i want to set the row size based on number of records fetched from the oracle database.kindly guide me
    Arjun

    What you need is to develop a table model which uses a database as the data source.
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#data

  • Please Help in Connecting to a Postgres database

    Hi,
    I installed the ODI 10.1.3.5 in my PC, I'm using a Windows Server 2003 R2 Standard Edition, I puzzled of how to connect to a Postgres Database. I downloaded a postgresql-8.1-413.jdbc3.jar driver and placed it in the \OraHome_1\oracledi\drivers. Then what will I do next?
    Thanks,
    Randy

    Hi CTS,
    That was helpful, But I already added Postgres in Topology.
    My problem now is how to create a Master Repository in Postgres?
    Here are my settings;
    Driver : org.postgresql.Driver
    URL : jdbc:postgresql://localhost:5432/mydatabase
    User : username
    Password : password
    I select PostgreSQL in the Technology, badluck I receives this error message.
    Error Detected during Repository Installation com.sunopsis.tools.core.exception.SnpsRuntimeException: com.sunopsis.tools.core.exception.SnpsRuntimeException: Unable to find the XML file corresponding to your technology.
    Please someone help me on this.
    Thanks,
    Randy

  • BO XI3.1: Support for Greenplum/PostGres Database

    Is Support for GreenPlum /Postgres database schedule for next service pack of BO XI3.1?
    With Postgres database - we have support only in Crystal and not in BO according to supported platform guide.
    Could you please advise whether we have scheduled the support for GreenPlum/Postgres database for BOXI 3.1 - in the next release of BOXI 3.1 SP2 ?
    Information from customer :
    - for Postgres database with ODBC drivers are working ok.
    - whether GreenPlum database is going to be supported in the next service pack
    - whether Postgres JDBC drivers could be used to Connect to GreenPlum Database instead of Postgres ODBC Drivers.
    Could you please advise on this database support as requested by customer ?
    Regards,
    Ganesh

    Hi, I've experienced using Greenplum database and odbc PostsgreSQl
    For BOE 3.1, you can create Webi, but not applicable with dashboard part. Where it cannot recognized the Postgre driver.
    Currently i'm trying to use another driver from DataDirect.
    Thats all for now.

  • ARD update crashed another Postgres database

    A few days ago I updated the remote desktop client on my OS X server to version 3.2.1 and after that a Postgres database that I had no longer works. I cannot connect to it and the Postgres service manager is no longer able to start my Postgres.
    How do I disable the remote desktop instance of postgres? What should I do? I'm completely clueless and desperate here.
    Thank you for your support,
    Cassiano

    Thanks Slade!
    I was also able to find a workaround using the SQL query:
    SHOW TABLES;
    That was also for a MySQL Database, and I don't have enough database experience to comment on how universal that implementation is .
    Nevertheless, my implementation is attached below.
    Cheers,
    Spex
    National Instruments
    To the pessimist, the glass is half empty; to the optimist, the glass is half full; to the engineer, the glass is twice as big as it needs to be...
    Attachments:
    DB List Tables Memory Leak Workaround1.zip ‏26 KB

Maybe you are looking for

  • Account requires an assignment to a CO object

    Hello dear all, The user posted a document in January 2010 for G/L Account I6XXXXX Then, in Februar 2010 the user defined this account I6XXXXX as a cost element In March 2010 we realized that we have discrepancies between GR55(CON2) and FAGLL03 for I

  • File dates and names missing from library

    I have recently had my hard drive replaced and started afresh. My old copy of iPhoto library downloaded photos into separate files by date order and showed the roll name I assigned. I could click on a little arrow on the left to show or hide the phot

  • Major SSD crash

    My startup SSD crashed while using FCP X. FCP X was getting slower and slower as it tried to deal with thousands of clips in a project which were the result of thousands of time code breaks. Fast forwarding and rewinding the tape got rid of a few hun

  • 2008 Mac won't recognise software updates?

    Currently on Mac OS x 10.5.8 and want to install latest - how do i do this?

  • IProcurement mapping for catageories and org

    Hi All, I have a requirement to restrict the catageries in IProcument based on the Org_id. Can any body help which tables i need to consider to map the catageries and org_id. Currently i am using the follwoing tables icx_cat_categories_tl , ICX_CAT_C