Sunday, April 24, 2011

Java Database Connectivity : Viewing Data

                                                       // Watch a video tutorial on videos page
How to establish a connection between front end and back end in just 10 Steps.
In my case, front end is Java GUI(using NetBeans IDE) and back end is MySql.

Database Connectivity(JDBC)

Steps :-
1 Create a database in your RDBMS(MySql in this example)
2 Create a table and insert some rows.
3 Open NetBeans and create a project
4 Add 'MySql JDBC Driver' Library in your project(Right click on project icon » Properties » Libraries » Add Library » MySql JDBC Driver).
5 Create a new JFrameForm under the project.
6 Insert a JTable swing component.
7 Edit it's content according to your requirement(Right click » choose Table Contents).
8 Under your package and before class starts write the following codes in the source tab.
   import java.sql.*;
   import javax.swing.JOptionPane;
   import javax.swing.table.DefaultTableModel;

9 Insert a button to view the data when we click.Write the coding on the button's actionPerformed event.
    DefaultTableModel model=(DefaultTableModel) jTable1.getModel();
    String sql="Select * from Table_name";
    try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/yourdatabasename","yourmysqlid","yourmysqlpassword");
/*As we are creating a connection on a local computer we will write the url as jdbc:mysql://localhost:3306 */
        Statement stmt=con.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        while (rs.next())
        {
            String no = rs.getString("NO");
            String title= rs.getString("TITLE");
            String auth= rs.getString("AUTHOR");
            String type= rs.getString("TYPE");
            String pub= rs.getString("PUB");
            String qty= rs.getString("QTY");
            String amt= rs.getString("AMOUNT");
            model.addRow(new Object []{
                no,title,auth,type,pub,qty,amt});
        }
    }
    catch(Exception e) {
        JOptionPane.showMessageDialog(this, e.getMessage());
    }
10 Change the codes in blue according to your database.

Run the file and you are done to view the contents in your database in GUI environment.
Please comment if you are facing any problem.
Run View
If this post helped you just give your few seconds in sharing this so that others could be helped too.

45 comments:

  1. What if i want to do the same thing but use postgreSQL instead of Mysql,
    waht changes will i need to make to your current code

    thanks

    ReplyDelete
  2. @Khanny the library and the connection URL for DriverManager will change..

    ReplyDelete
  3. hey thanks a lot :)

    ReplyDelete
  4. when i click the view Data button several times, the data again show themselves again and again making the table bigger and bigger.

    how can i make it as a refresh button?

    ReplyDelete
  5. @Anonymous

    model.setRowCount(0);

    Add the above code BELOW the line DefaultTableModel model=(DefaultTableModel) jTable1.getModel();

    ReplyDelete
  6. @Rohan

    Thanks alot, it worked :)

    ReplyDelete
  7. i am having error as com.mysql.jdbc.driver

    ReplyDelete
  8. @Anonymous u have not imported the correct library

    ReplyDelete
  9. I cant connect to mysql server it says connection is not established and I cant create the database, cant you help it seems that I need to install a program and link to mysql admin tools

    ReplyDelete
  10. @Anonymous try reconfiguring your mysql settings.

    ReplyDelete
  11. how do i reconfigure mysql settings
    which ones are the correct configurations

    ReplyDelete
  12. I get this error when running the file:
    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: org.jdesktop.swingbinding.JTableBinding$BindingTableModel cannot be cast to javax.swing.table.DefaultTableModel

    ReplyDelete
  13. hello, nice tutorial and works perfectly. this shows the data that we enter in Mysql into the java interface. is there a way to do it other way round? that is enter data in the interface and view it in mysql command line client? could you show the steps for that as well? thanks in advance.

    ReplyDelete
  14. Error is there showing message

    Exception in thread "AWT-EventQueue-0" javax.persistence.PersistenceException: No Persistence provider for EntityManager named cybcafdbPU: Provider named oracle.toplink.essentials.PersistenceProvider threw unexpected exception at create EntityManagerFactory:
    oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException
    Local Exception Stack:
    Exception [TOPLINK-30005] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException
    Exception Description: An exception was thrown while searching for persistence archives with ClassLoader: sun.misc.Launcher$AppClassLoader@17590db
    Internal Exception: javax.persistence.PersistenceException: Exception [TOPLINK-28018] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.EntityManagerSetupException
    Exception Description: predeploy for PersistenceUnit [cybcafdbPU] failed.
    Internal Exception: Exception [TOPLINK-30007] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException
    Exception Description: An exception was thrown while loading class: cybercafe.Login_1 to check whether it implements @Entity, @Embeddable, or @MappedSuperclass.
    Internal Exception: java.lang.ClassNotFoundException: cybercafe.Login_1

    ReplyDelete
  15. How to connect to Access Database Table using this code.

    ReplyDelete
  16. thanks it is very helpful .plz also post report generation in mysql with java as front end.

    ReplyDelete
  17. Sir Plz send Search function in video my
    id am very thaksfull to you
    waqary705@gmail.com

    ReplyDelete
  18. great tutorial...
    but unfortunately neither i am able to view the data nor i am getting any error or exception... as i press the View data button, after few seconds of execution i get a dialog box:

    "Communication Link Failure: The Last Packet Sent Successfully to the Server was 0 milliseconds ago. The driver has not received any packets from the Server. "

    Kindly assist me through it and tell me how to correct my mistake?

    Thanks!

    ReplyDelete
  19. doesnr work :( plz help me.. using jdeveloper and when i click the button there is nothin :( have mc access..dunno why..

    ReplyDelete
  20. its very helpful.................

    ReplyDelete
  21. thanks............it is very helpful.
    I can see the data.
    But after four rows.
    Can you help me to display data from the first row itself?

    ReplyDelete
  22. @Anonymous
    i think you have not followed the 7th step...

    So, In the design mode right click your table and select Edit Contents and choose 0 as the number of rows

    ReplyDelete
  23. It works....
    Thanks a lot.............

    ReplyDelete
  24. Can you please tell the code when the back end is access or excel.
    or how to convert database in excel to My sql??
    plz rply ASAP..

    ReplyDelete
  25. How to clear the data which has been viewed and display or view contents of another table..??

    ReplyDelete
  26. I have my connect jframe working and connecting. What I can do to maintain the connection and open the new window automatic to start the search? Both jframe are working property with the ResultSet in the second frame. Thank you.

    ReplyDelete
  27. @author: I want to populate my JTables from my dataBase....
    Can you give some idea? Thankyou..
    Also, when i add/update/delete data i want to refresh those jTables.. and Jlists(in case of deletion) at the same form..

    ReplyDelete
  28. anyone provide me full source code please

    ReplyDelete
  29. can dis code be also applied for ecllipse??

    ReplyDelete
  30. sir can u plz send me java in frontend & oracle in backend connectivity steps...i made a project using netbeans ide...still it is not connecting to database ,i have already used connectivty videos on you tube. plz help me sir...

    ReplyDelete
  31. DefaultTableModel model=(DefaultTableModel) jTable1.getModel();
    what is this mean i got error in jtable1

    ReplyDelete
  32. Hello Sir it is very helpful for me bt i want to view my data in textfield..
    so how can i fetch that data from database in textfeild

    ReplyDelete
  33. DefaultTableModel model = (DefaultTableModel)mdel.getModel();
    cannot find the symbol is reporting when it is s tried using javafx...
    help me out asap

    ReplyDelete
  34. The code works great, but when I selected view data, it gave me there error that my Table did not exist. I have created a table in the MySql database and everything was connected. I have also entered the table name and Db name correctly in the code. I even tried changing to upper and lower case. No Joy. Any help is appreciated.

    ReplyDelete
  35. Thank you bro you saved my time...

    ReplyDelete
  36. great tutorial...
    but unfortunately neither i am able to view the data nor i am getting any error or exception... as i press the View data button, after few seconds of execution i get a dialog box:

    "Communication Link Failure: The Last Packet Sent Successfully to the Server was 0 milliseconds ago. The driver has not received any packets from the Server. "

    Kindly assist me through it and tell me how to correct my mistake plzzzz?

    Thanks!

    ReplyDelete
    Replies
    1. Re-configure your mysql server and verify that it's running on the 3306 port and also check the box which says 'Install MySQL as Windows Service'

      Delete
  37. Its saying build successful but im not able to view anything in my table even when I press the button!!

    ReplyDelete
    Replies
    1. Make sure you are connecting with right database and table which contains data. Also see the Output window in NetBeans to check if there is any error.

      Delete
  38. how to display the data into another form?

    ReplyDelete
  39. how to link a pdf file with my java software??

    ReplyDelete
  40. Good one, very good examples, you may please provide some other examples for better understanding of the GUI and mysql connecting environment.

    ReplyDelete
  41. the data is getting viewed only after i click into the table one by one. can u help me with this error

    ReplyDelete