Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 1 of 1

Thread: Java Swing Tables ( JTable Models ) to connect to Database using Table Models

  1. #1
    Junior Member
    Join Date
    Jan 2010
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Java Swing Tables ( JTable Models ) to connect to Database using Table Models

    hey everyone,
    please someone help me out in Connecting JTable to Database..

    I've created 5 files, here are the codes, pls temme how should i proceed further to connect it to database( JTable to Database using Table Models)

    1. Attendance.java ( Main swing File in wich i've created a table using JTable )
    /*
     * Attendance.java
     *
     * Created on 9 Jan, 2010, 11:18:47 PM
     */
     
    package attendance;
     
    public class Attendance extends javax.swing.JFrame {
     
        /** Creates new form Attendance */
        public Attendance() {
            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">                          
        private void initComponents() {
     
            jScrollPane1 = new javax.swing.JScrollPane();
            urviAttendance = new javax.swing.JTable();
            jLabel1 = new javax.swing.JLabel();
            currentDate = new javax.swing.JTextField();
     
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
     
            urviAttendance.setBorder(new javax.swing.border.MatteBorder(null));
            urviAttendance.setFont(new java.awt.Font("Comic Sans MS", 1, 14)); // NOI18N
            urviAttendance.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                    {null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                    {null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                    {null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                    {null, null, null, null, null, null, null, null, null, null, null, null, null, null}
                },
                new String [] {
                    "Sr. No.", "Code", "Name", "Shift", "Shift In", "In", "Late", "Shift Out", "Out", "Early", "Working Hours", "Over Time", "Status", "Remark"
                }
            ) {
                Class[] types = new Class [] {
                    java.lang.Integer.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
                };
     
                public Class getColumnClass(int columnIndex) {
                    return types [columnIndex];
                }
            });
            urviAttendance.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
            urviAttendance.setRowHeight(17);
            jScrollPane1.setViewportView(urviAttendance);
     
            jLabel1.setText("Date :");
     
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jLabel1)
                    .addGap(18, 18, 18)
                    .addComponent(currentDate, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(528, Short.MAX_VALUE))
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 699, Short.MAX_VALUE)
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(currentDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 313, Short.MAX_VALUE))
            );
     
            pack();
        }// </editor-fold>                        
     
     
        /**
        * @param args the command line arguments
        */
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Attendance().setVisible(true);
                }
            });
        }
     
        // Variables declaration - do not modify                     
        javax.swing.JTextField currentDate;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTable urviAttendance;
        // End of variables declaration                   
     
    }

    2. DatabaseConnectivity.java ( For connecting it to database )

    package attendance;
    import java.sql.*;
     
     
    public class DatabaseConnectivity {
     
     
     
        Connection con = null;
    	ResultSet rs = null;
    	public DatabaseConnectivity()throws MyException
    	{
    		try{
    		Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    		con = DriverManager.getConnection("jdbc:odbc:Attendance"," "," ");
    		}catch(ClassNotFoundException ce)
    		{
    			throw new MyException("Database Drivers not found");
    		}catch(SQLException se)
    		{
    			throw new MyException("SQL Exception : "+se.getMessage());
    		}
    	}
    	public boolean createTable()
    	{
    		String q = "create table Employees (EmpID int, Name varchar(20), Address varchar(100) )";
    		try{
    		Statement st = con.createStatement();
    		st.executeUpdate(q);
    		return true;
    		}catch(SQLException se)
    		{
    			return false;
    		}
    	}
    	public void add(int empid, String name, String address)throws MyException
    	{
    		try{
    		String q = "insert into Employees values(" + empid+",' "+name+" ','"+address+"')";
    		System.out.println("Query : "+q);
    		Statement st = con.createStatement();
    		int i = st.executeUpdate(q);
    		System.out.println(i+" records added");
    		}catch(SQLException se)
    		{
    			throw new MyException("Error occurred while trying to add new record! \n"+se.getMessage());
    		}
    	}
    	public void close()
    	{
    		con = null;
    	}
    }

    3. TestDatabase.java ( To check whether database connection is proper or not )
    package attendance;
     
     
    public class TestDatabase {
     
     
    	public static void main(String arg[])
    	{
    		try{
    		DatabaseConnectivity db = new DatabaseConnectivity();
    		if(db.createTable())
    			System.out.println("Table has been created!");
    		else
    			System.out.println("Table already exists!");
    		db.add(101,"abc","mumbai");
    		db.close();
    		}catch(MyException e)
    		{
    			System.out.println(e.getMessage());
    		}
    	}
    }

    4. MyException.java ( As there are many exceptions in SQL, i've created my own Exception )

    package attendance;
     
    public class MyException extends Exception {
     
        /**
         * Creates a new instance of <code>MyException</code> without detail message.
         */
        public MyException() {
        }
     
     
        /**
         * Constructs an instance of <code>MyException</code> with the specified detail message.
         * @param msg the detail message.
         */
        public MyException(String msg) {
            super(msg);
        }
    }

    5. MyTableModel.java ( To connect my JTable i.e. Attendance.java to Database using Table Models )

    package attendance;
     
    import javax.swing.event.TableModelListener;
    import javax.swing.table.TableModel;
     
     
    public class MyTableModel implements TableModel{
     
     
        public int getRowCount() {
            return getRowCount();     
        }
     
        public int getColumnCount() {
            return getColumnCount();
        }
     
        public String getColumnName(int columnIndex) {
            return getColumnName(columnIndex);
        }
     
        public Class<?> getColumnClass(int columnIndex) {
            return getColumnClass(columnIndex);
        }
     
        public boolean isCellEditable(int rowIndex, int columnIndex) {
     
        }
     
        public Object getValueAt(int rowIndex, int columnIndex) {
            return getValueAt(rowIndex, columnIndex);
        }
     
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
     
        }
     
        public void addTableModelListener(TableModelListener l) {
     
        }
     
        public void removeTableModelListener(TableModelListener l) {
     
        }
     
    }

    pls help me .. pls...hav 2 complete dis project before 30th January..
    thanx in advance !!!

    Regards,
    Java Programmer.
    Last edited by helloworld922; January 27th, 2010 at 02:06 AM. Reason: Please use [code] tags!


Similar Threads

  1. How to Connect to an Excel Spreadsheet using JDBC in Java
    By JavaPF in forum JDBC and Database Tutorials
    Replies: 14
    Last Post: August 27th, 2013, 11:57 AM
  2. set the slider's models (range)
    By chronoz13 in forum AWT / Java Swing
    Replies: 1
    Last Post: November 28th, 2009, 11:59 PM
  3. java swing help
    By JM_4ever in forum AWT / Java Swing
    Replies: 3
    Last Post: October 7th, 2009, 06:42 AM
  4. merging two tables from two diffrent htmls files using java
    By sukant_at in forum File I/O & Other I/O Streams
    Replies: 3
    Last Post: September 1st, 2009, 05:13 AM
  5. merging two tables from two diffrent htmls files using java
    By sukant_at in forum File I/O & Other I/O Streams
    Replies: 2
    Last Post: August 7th, 2009, 12:48 PM