How to assign the resultset to grid in swings.

Posted on 2011-10-31
Last Modified: 2012-05-12
Here in this code the result in displayed on window. How to put the result in grid or something like grid in swings
//Select data from table
import java.sql.*;
class sqlselect
public static void main(String args[]) throws Exception
            String ename,ecity;

            Connection conn;      
            Statement stmt;
            ResultSet rs;

            //initialize and load the JDBC-ODBC Driver
            //to get a datbase connection
            //to create a statement object to execute SQL statement
            //Sends the sql statemtent to the DBMS & executes
            rs=stmt.executeQuery("select * from emp");
Question by:searchsanjaysharma
    LVL 47

    Expert Comment

    You can have a JTable and associate its TableModel object with the ResultSet
    LVL 47

    Expert Comment

    LVL 20

    Expert Comment

    by:chaitu chaitu
    LVL 47

    Expert Comment


    This is another way which uses additional Jar and DbUtils class:
    LVL 47

    Expert Comment

    and this simple code snippet how to transfer ResultSet to JTable form

    // TableModel definition
    String[] tableColumnsName = {"col 1","col 2","col 3"}; 
    DefaultTableModel aModel = (DefaultTableModel) aTable.getModel();
    // the query
    ResultSet rs = 
       statement.executeQuery("select col1,col2,col3 from mytable");
    // Loop through the ResultSet and transfer in the Model
    java.sql.ResultSetMetaData rsmd = rs.getMetaData();
    int colNo = rsmd.getColumnCount();
     Object[] objects = new Object[colNo];
     // tanks to umit ozkan for the bug fix!
     for(int i=0;i<colNo;i++){

    Open in new window

    LVL 1

    Expert Comment

    LVL 47

    Expert Comment

    This is actually a very good example
    from the above link;
    - I just
    tested it with my mySql connection.
    I already put your driver and URL -
    if you compile it and paste the query
    select * from emp
    into the query field
    (you don't even need URL, as it is already encoded - you'll see
    the table coming up)
    I belive it is very good illustartion how
    table model from sql works - everything determined by the resultSet

    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.Statement;
    import java.util.Vector;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.table.AbstractTableModel;
    public class DatabaseTest extends JFrame {
      JTextField hostField;
      JTextField queryField;
      QueryTableModel qtm;
      public DatabaseTest() {
        super("Database Test Frame");
        setSize(350, 200);
        qtm = new QueryTableModel();
        JTable table = new JTable(qtm);
        JScrollPane scrollpane = new JScrollPane(table);
        JPanel p1 = new JPanel();
        p1.setLayout(new GridLayout(3, 2));
        p1.add(new JLabel("Enter the Host URL: "));
        p1.add(hostField = new JTextField());
        p1.add(new JLabel("Enter your query: "));
        p1.add(queryField = new JTextField());
        p1.add(new JLabel("Click here to send: "));
        JButton jb = new JButton("Search");
        jb.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
        getContentPane().add(p1, BorderLayout.NORTH);
        getContentPane().add(scrollpane, BorderLayout.CENTER);
      public static void main(String args[]) {
        DatabaseTest tt = new DatabaseTest();
    //A basic implementation of the TableModel interface that fills out a Vector of
    //String[] structures from a query's result set.
    class QueryTableModel extends AbstractTableModel {
      Vector cache; // will hold String[] objects . . .
      int colCount;
      String[] headers;
      Connection db;
      Statement statement;
      String currentURL;
        Connection conn;
      public QueryTableModel() {
        cache = new Vector();
      public String getColumnName(int i) {
        return headers[i];
      public int getColumnCount() {
        return colCount;
      public int getRowCount() {
        return cache.size();
      public Object getValueAt(int row, int col) {
        return ((String[]) cache.elementAt(row))[col];
      public void setHostURL(String url) {
        if (url.equals(currentURL)) {
          // same database, we can leave the current connection open
        // Oops . . . new connection required
        currentURL = url;
      // All the real work happens here; in a real application,
      // we'd probably perform the query in a separate thread.
      public void setQuery(String q) {
        cache = new Vector();
        try {
          // Execute the query and store the result set and its metadata
          ResultSet rs = statement.executeQuery(q);
          ResultSetMetaData meta = rs.getMetaData();
          colCount = meta.getColumnCount();
          // Now we must rebuild the headers array with the new column names
          headers = new String[colCount];
          for (int h = 1; h <= colCount; h++) {
            headers[h - 1] = meta.getColumnName(h);
          // and file the cache with the records from our query. This would
          // not be
          // practical if we were expecting a few million records in response
          // to our
          // query, but we aren't, so we can do this.
          while ( {
            String[] record = new String[colCount];
            for (int i = 0; i < colCount; i++) {
              record[i] = rs.getString(i + 1);
          fireTableChanged(null); // notify everyone that we have a new table.
        } catch (Exception e) {
          cache = new Vector(); // blank it out and keep going.
      public void initDB(String url) {
        try {
                  db =   DriverManager.getConnection("jdbc:odbc:mydsn","","");
          statement = db.createStatement();
        } catch (Exception e) {
          System.out.println("Could not initialize the database.");
      public void closeDB() {
        try {
          if (statement != null) {
          if (db != null) {
        } catch (Exception e) {
          System.out.println("Could not close the current connection.");

    Open in new window

    LVL 47

    Accepted Solution

    This is how it looks for my test_table query.

    Just takes a query and creates JTable based on the result set

    Author Closing Comment


    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Join & Write a Comment

    Suggested Solutions

    Title # Comments Views Activity
    copyEvens challenge 6 47
    countHi challenge 25 63
    return in catch statement 1 33
    Impossible to extract MSI from new JAVA releases 2 7
    Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
    Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
    Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
    The viewer will learn how to implement Singleton Design Pattern in Java.

    755 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now