displaying data from database in JTable displaying data from database in JTable
Menu
 

Likes Likes:  0
Dislikes Dislikes:  0
Results 1 to 3 of 3

Thread: displaying data from database in JTable

  1. #1
    Right Off the Assembly Line Reputation
    Join Date
    Nov 2007
    Posts
    14
    Post Thanks / Like

    General displaying data from database in JTable

    Hello everybody!
    Can anyone tell me the code for how to display data from table in database in a JTable in java. I am using java 1.5 and MS-Access.

  2. #2
    Wise Old Owl Reputation JGuru's Avatar
    Join Date
    Dec 2005
    Location
    Space-time continuum
    Posts
    1,688
    Post Thanks / Like

    General Re: displaying data from database in JTable

    @Peyosh, Here goes the answer to your question.

    Here is the JAVA code for JDBC Connectivity:

    //This will fetch the data from a table & display the output in a JTable


    //JDBCAdapter.java
    /*
    * @(#)JDBCAdapter.java 1.16
    */

    /**
    * An adaptor, transforming the JDBC interface to the TableModel interface.
    *
    * @version 1.20
    * @author JGuru
    */

    import java.util.Vector;
    import java.sql.*;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.event.TableModelEvent;

    public class JDBCAdapter extends AbstractTableModel {
    Connection connection;
    Statement statement;
    ResultSet resultSet;
    String[] columnNames = {};
    Vector rows = new Vector();
    ResultSetMetaData metaData;

    public JDBCAdapter(String url, String driverName,
    String user, String passwd) {
    try {
    Class.forName(driverName);
    System.out.println("Opening db connection");

    connection = DriverManager.getConnection(url, user, passwd);
    statement = connection.createStatement();
    }
    catch (ClassNotFoundException ex) {
    System.err.println("Cannot find the database driver classes.");
    System.err.println(ex);
    }
    catch (SQLException ex) {
    System.err.println("Cannot connect to this database.");
    System.err.println(ex);
    }
    }

    public void executeQuery(String query) {
    if (connection == null || statement == null) {
    System.err.println("There is no database to execute the query.");
    return;
    }
    try {
    resultSet = statement.executeQuery(query);
    metaData = resultSet.getMetaData();

    int numberOfColumns = metaData.getColumnCount();
    columnNames = new String[numberOfColumns];
    // Get the column names and cache them.
    // Then we can close the connection.
    for(int column = 0; column < numberOfColumns; column++) {
    columnNames[column] = metaData.getColumnLabel(column+1);
    }

    // Get all rows.
    rows = new Vector();
    while (resultSet.next()) {
    Vector newRow = new Vector();
    for (int i = 1; i <= getColumnCount(); i++) {
    newRow.addElement(resultSet.getObject(i));
    }
    rows.addElement(newRow);
    }
    // close(); Need to copy the metaData, bug in jdbcdbc driver.
    fireTableChanged(null); // Tell the listeners a new table has arrived.
    }
    catch (SQLException ex) {
    System.err.println(ex);
    }
    }

    public void close() throws SQLException {
    System.out.println("Closing db connection");
    resultSet.close();
    statement.close();
    connection.close();
    }

    protected void finalize() throws Throwable {
    close();
    super.finalize();
    }

    //////////////////////////////////////////////////////////////////////////
    //
    // Implementation of the TableModel Interface
    //
    //////////////////////////////////////////////////////////////////////////

    // MetaData

    public String getColumnName(int column) {
    if (columnNames[column] != null) {
    return columnNames[column];
    } else {
    return "";
    }
    }

    public Class getColumnClass(int column) {
    int type;
    try {
    type = metaData.getColumnType(column+1);
    }
    catch (SQLException e) {
    return super.getColumnClass(column);
    }

    switch(type) {
    case Types.CHAR:
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
    return String.class;

    case Types.BIT:
    return Boolean.class;

    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.INTEGER:
    return Integer.class;

    case Types.BIGINT:
    return Long.class;

    case Types.FLOAT:
    case Types.DOUBLE:
    return Double.class;

    case Types.DATE:
    return java.sql.Date.class;

    default:
    return Object.class;
    }
    }

    public boolean isCellEditable(int row, int column) {
    try {
    return metaData.isWritable(column+1);
    }
    catch (SQLException e) {
    return false;
    }
    }

    public int getColumnCount() {
    return columnNames.length;
    }

    // Data methods

    public int getRowCount() {
    return rows.size();
    }

    public Object getValueAt(int aRow, int aColumn) {
    Vector row = (Vector)rows.elementAt(aRow);
    return row.elementAt(aColumn);
    }

    public String dbRepresentation(int column, Object value) {
    int type;

    if (value == null) {
    return "null";
    }

    try {
    type = metaData.getColumnType(column+1);
    }
    catch (SQLException e) {
    return value.toString();
    }

    switch(type) {
    case Types.INTEGER:
    case Types.DOUBLE:
    case Types.FLOAT:
    return value.toString();
    case Types.BIT:
    return ((Boolean)value).booleanValue() ? "1" : "0";
    case Types.DATE:
    return value.toString(); // This will need some conversion.
    default:
    return "\""+value.toString()+"\"";
    }

    }

    public void setValueAt(Object value, int row, int column) {
    try {
    String tableName = metaData.getTableName(column+1);
    // Some of the drivers seem buggy, tableName should not be null.
    if (tableName == null) {
    System.out.println("Table name returned null.");
    }
    String columnName = getColumnName(column);
    String query =
    "update "+tableName+
    " set "+columnName+" = "+dbRepresentation(column, value)+
    " where ";
    // We don't have a model of the schema so we don't know the
    // primary keys or which columns to lock on. To demonstrate
    // that editing is possible, we'll just lock on everything.
    for(int col = 0; col<getColumnCount(); col++) {
    String colName = getColumnName(col);
    if (colName.equals("")) {
    continue;
    }
    if (col != 0) {
    query = query + " and ";
    }
    query = query + colName +" = "+
    dbRepresentation(col, getValueAt(row, col));
    }
    System.out.println(query);
    System.out.println("Not sending update to database");
    // statement.executeQuery(query);
    }
    catch (SQLException e) {
    // e.printStackTrace();
    System.err.println("Update failed");
    }
    Vector dataRow = (Vector)rows.elementAt(row);
    dataRow.setElementAt(value, column);

    }
    }

    The second file is as follows:
    //TableExample.java
    /*
    * @(#)TableExample.java
    */

    /**
    * A a UI around the JDBCAdaptor, allowing database data to be interactively
    * fetched, sorted and displayed using Swing.
    *
    * NOTE: This example uses a modal dialog via the static convenience methods in
    * the JOptionPane. Use of modal dialogs requires JDK 1.1.4 or greater.
    *
    * @version 1.19
    * @author JGuru
    */

    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    import javax.swing.border.*;

    public class TableExample implements LayoutManager {
    static String[] ConnectOptionNames = { "Connect" };
    static String ConnectTitle = "Connection Information";

    Dimension origin = new Dimension(0, 0);

    JButton fetchButton;
    JButton showConnectionInfoButton;

    JPanel connectionPanel;
    JFrame frame; // The query/results window.

    JLabel userNameLabel;
    JTextField userNameField;
    JLabel passwordLabel;
    JTextField passwordField;
    // JLabel queryLabel;
    JTextArea queryTextArea;
    JComponent queryAggregate;
    JLabel serverLabel;
    JTextField serverField;
    JLabel driverLabel;
    JTextField driverField;

    JPanel mainPanel;

    TableSorter sorter;
    JDBCAdapter dataBase;
    JScrollPane tableAggregate;

    /**
    * Brings up a JDialog using JOptionPane containing the connectionPanel.
    * If the user clicks on the 'Connect' button the connection is reset.
    */
    void activateConnectionDialog() {
    if(JOptionPane.showOptionDialog(tableAggregate, connectionPanel, ConnectTitle,
    JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE,
    null, ConnectOptionNames, ConnectOptionNames[0]) == 0) {
    connect();
    frame.setVisible(true);
    }
    else if(!frame.isVisible())
    System.exit(0);
    }

    /**
    * Creates the connectionPanel, which will contain all the fields for
    * the connection information.
    */
    public void createConnectionDialog() {
    // Create the labels and text fields.
    userNameLabel = new JLabel("User name: ", JLabel.RIGHT);
    userNameField = new JTextField("guest");

    passwordLabel = new JLabel("Password: ", JLabel.RIGHT);
    passwordField = new JTextField("trustworthy");

    serverLabel = new JLabel("Database URL: ", JLabel.RIGHT);
    serverField = new JTextField("jdbcdbc:mydsn");
    //Where 'mydsn' is the DSN (Data Source Name you have created using the ODBC icon in Windows Control Panel.
    driverLabel = new JLabel("Driver: ", JLabel.RIGHT);
    driverField = new JTextField("sun.jdbc.odbc.JdbcOdbcDriver");


    connectionPanel = new JPanel(false);
    connectionPanel.setLayout(new BoxLayout(connectionPanel,
    BoxLayout.X_AXIS));

    JPanel namePanel = new JPanel(false);
    namePanel.setLayout(new GridLayout(0, 1));
    namePanel.add(userNameLabel);
    namePanel.add(passwordLabel);
    namePanel.add(serverLabel);
    namePanel.add(driverLabel);

    JPanel fieldPanel = new JPanel(false);
    fieldPanel.setLayout(new GridLayout(0, 1));
    fieldPanel.add(userNameField);
    fieldPanel.add(passwordField);
    fieldPanel.add(serverField);
    fieldPanel.add(driverField);

    connectionPanel.add(namePanel);
    connectionPanel.add(fieldPanel);
    }

    public TableExample() {
    mainPanel = new JPanel();

    // Create the panel for the connection information
    createConnectionDialog();

    // Create the buttons.
    showConnectionInfoButton = new JButton("Configuration");
    showConnectionInfoButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    activateConnectionDialog();
    }
    }
    );

    fetchButton = new JButton("Fetch");
    fetchButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    fetch();
    }
    }
    );

    // Create the query text area and label.
    queryTextArea = new JTextArea("SELECT * FROM titles", 25, 25);
    queryAggregate = new JScrollPane(queryTextArea);
    queryAggregate.setBorder(new BevelBorder(BevelBorder.LOWERED));

    // Create the table.
    tableAggregate = createTable();
    tableAggregate.setBorder(new BevelBorder(BevelBorder.LOWERED));

    // Add all the components to the main panel.
    mainPanel.add(fetchButton);
    mainPanel.add(showConnectionInfoButton);
    mainPanel.add(queryAggregate);
    mainPanel.add(tableAggregate);
    mainPanel.setLayout(this);

    // Create a Frame and put the main panel in it.
    frame = new JFrame("TableExample");
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {System.exit(0);}});
    frame.setBackground(Color.lightGray);
    frame.getContentPane().add(mainPanel);
    frame.pack();
    frame.setVisible(false);
    frame.setBounds(200, 200, 640, 480);

    activateConnectionDialog();
    }

    public void connect() {
    dataBase = new JDBCAdapter(
    serverField.getText(),
    driverField.getText(),
    userNameField.getText(),
    passwordField.getText());
    sorter.setModel(dataBase);
    }

    public void fetch() {
    dataBase.executeQuery(queryTextArea.getText());
    }

    public JScrollPane createTable() {
    sorter = new TableSorter();

    //connect();
    //fetch();

    // Create the table
    JTable table = new JTable(sorter);
    // Use a scrollbar, in case there are many columns.
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

    // Install a mouse listener in the TableHeader as the sorter UI.
    sorter.addMouseListenerToHeaderInTable(table);

    JScrollPane scrollpane = new JScrollPane(table);

    return scrollpane;
    }

    public static void main(String s[]) {
    new TableExample();
    }

    public Dimension preferredLayoutSize(Container c){return origin;}
    public Dimension minimumLayoutSize(Container c){return origin;}
    public void addLayoutComponent(String s, Component c) {}
    public void removeLayoutComponent(Component c) {}
    public void layoutContainer(Container c) {
    Rectangle b = c.getBounds();
    int topHeight = 90;
    int inset = 4;
    showConnectionInfoButton.setBounds(b.width-2*inset-120, inset, 120, 25);
    fetchButton.setBounds(b.width-2*inset-120, 60, 120, 25);
    // queryLabel.setBounds(10, 10, 100, 25);
    queryAggregate.setBounds(inset, inset, b.width-2*inset - 150, 80);
    tableAggregate.setBounds(new Rectangle(inset,
    inset + topHeight,
    b.width-2*inset,
    b.height-2*inset - topHeight));
    }

    }

    Both the 2 files are needed for Compiling & running the program.
    To Compile:

    javac TableExample.java

    To run:

    java TableExample

    You must also configure & create a new DSN from the 'ODBC' icon
    in the Control Panel.

    See JDBC Tutorial Click here :http://java.sun.com/docs/books/tutor...ics/index.html

    Also see JDBC 2.0 Fundamentals Tutorial Click here : http://java.sun.com/developer/online...ro/JDBC20.html


    Also see How to use Tables : http://java.sun.com/docs/books/tutor...nts/table.html

    You also need to study & understand JFC(Java Foundation Classes).
    Last edited by JGuru; 30-04-2008 at 08:29 PM. Reason: To make some corrections
    * Imagination is more important than knowledge.
    -Albert Einstein

  3. #3
    Right Off the Assembly Line Reputation
    Join Date
    Nov 2007
    Posts
    14
    Post Thanks / Like

    General Re: displaying data from database in JTable

    thank u JGuru. your help will be highly beneficial for me. thank u once again

Similar Threads

  1. how to display data from mysql database in java
    By tushar087 in forum Programming
    Replies: 5
    Last Post: 27-10-2008, 02:26 AM
  2. Help Adsense ads not displaying
    By prabhatmohit in forum QnA (read only)
    Replies: 8
    Last Post: 28-06-2008, 03:21 PM
  3. want to create a database for my excel data?
    By raja2281 in forum Programming
    Replies: 2
    Last Post: 16-06-2008, 02:26 AM
  4. Help Help Help Help! Images Not Displaying
    By Shasanka_Gogoi in forum Mobiles and Tablets
    Replies: 5
    Last Post: 27-03-2007, 10:17 PM
  5. How to retrive data from mysql database dynamically
    By Butterfly in forum QnA (read only)
    Replies: 9
    Last Post: 04-11-2004, 05:30 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •