Thursday, April 28, 2011

Java Database Connectivity : Inserting Data

After viewing the data of a database in GUI, now we will learn how to insert the data through GUI in database.

Database Connectivity(JDBC)
1 Follow the 1-5 steps of Viewing Data in GUI.
   Note: It is not necessary to insert some rows in the table in the 2nd step.
2 In the design view,insert text-fields according to your database and a submit button.
3 Under your package and before class starts write the following codes in the source tab.
  import java.sql.*; 
  import javax.swing.JOptionPane;
4 Write the coding on the button's actionPerformed event for the connectivity.
   try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/database1","root","");
        Statement stmt=con.createStatement();

      }
   catch(Exception e) {
        JOptionPane.showMessageDialog(this, e.getMessage());
    }
5 Now, in the try block below the line Statement stmt=con.createStatement(); , write the code for taking input from the user through the text-fields you created earlier and for executing your sql query.
         String no = jTextField1.getText();
     String title = jTextField2.getText();
     String auth = jTextField3.getText();
     String sql="Insert into library values('"+(no)+"','"+(title)+"','"+(auth)+"')";
     stmt.executeUpdate(sql);
    
Note: In the brackets first symbol is a single apostrophe ( ' ) and then a double inverted comma ( " ). Same will be followed before and after each variable.
7 Change the codes in blue according to your database.
8 Run the file(Shift + F6) and you are ready to enter the data through your GUI.
Run View

41 comments:

  1. OK i have done all of this, but how do you get the message; Information added to database

    ReplyDelete
  2. @Khanny
    Below the line stmt.executeUpdate(sql);
    You can write the following-
    JOptionPane.showMessageDialog(this, "Data Added!);

    ReplyDelete
  3. Hi rohan, brother let me thank you for all the support you are providing to us. I really appreciate your work. Iam working on my project connected to a database, now my problem is how to deploy it after am done so that it i will contain all the resources including the database for the user to install. Thanks in advance bro.
    my email itpioneer2008@yahoo.com

    ReplyDelete
  4. @itpioneer2008
    if u will run ur project on a system where MySQL is already installed, then you can run all sql queries(including the creation of database) as soon as the app runs i.e windowOpened property
    but if u are spreading ur app to all, then u have to setup a database server over the internet and then the app can connect to it through TCP/IP.

    Also, create a runnable file for ur project otherwise u will have to install a java IDE first to run the app.
    For this, u can read - How to make JAR files using NetBeans IDE

    ReplyDelete
  5. hi rohan,nice tutorial. after following all the above steps,i get an error message in the dialog box:
    Communication link failure
    the last packet sent to the server was 0 milliseconds ago. The driver has not received any packets for the server.

    what could be the problem? please reply ASAP...thanks!

    ReplyDelete
  6. @Anonymous It often occurs on Win7, Go to start and type 'MySQL Server Instance Config Wizard' and reconfigure your MySQL settings and try it again it will surely work...

    ReplyDelete
  7. reconfigured it...but still doesnt work :(
    did a standard reconfig. but shows the same error! anything else that i can try out?

    ReplyDelete
  8. do i need to configure mysql/odbc driver in system DNS from administrative tools?

    ReplyDelete
  9. hello,i did this an got an error..
    "You have an error in your SQL Syntax.Check the manual that corresponds to your MYSQL server version for the right syntax to use near "","","", at line1

    ReplyDelete
  10. Anonymous said...

    reconfigured it...but still doesnt work :(
    did a standard reconfig. but shows the same error! anything else that i can try out?


    Check "Install as a windows service".

    ReplyDelete
  11. Anonymous said...
    "You have an error in your SQL Syntax.Check the manual that corresponds to your MYSQL server version for the right syntax to use near "","","", at line1

    You have made a mistake in step 5.
    Check that you are not passing empty values.


    In future, please comment as Name/URL..

    ReplyDelete
  12. nah! wont run! already installed as windows service. also tried out the example that you have specified here! still the same error! :(

    ReplyDelete
  13. @Aditya

    1 Check, you imported the correct library.
    2 Check, if you are able to open MySQL command-line client.
    3 Ensure you chose 3306 as port number while configuring MySQL.
    4 Disable your anti-virus and try again!

    ReplyDelete
  14. hey its done! thanks a lot for the guidance! :)

    ReplyDelete
  15. Thanx a lot for this awesome site..
    Problem :
    I tried the same with my form with many textfields but when i pressed submmit button
    error is "com.mysql.jdbc.Driver"

    Please HELP
    i am in an urgent need.

    using NetBeans 6.5
    My SQL 5.0.13
    my email id is priyanjan.kumar19@gmail.com

    Please help.
    Thanx in advance.

    ReplyDelete
  16. @Anonymous Right-click on your project>> Libraries>> Add Library>> MySQL JDBC Driver

    ReplyDelete
  17. how we clear the textfield after the data added ?

    ReplyDelete
  18. @dani add the following code :
    jTextField1.setText("");
    jTextField2.setText("");
    jTextField3.setText("");

    Below this line
    String sql="Insert into library values('"+(no)+"','"+(title)+"','"+(auth)+"')";

    ReplyDelete
  19. thanks, your site is very helpful for newbie like me :)

    ReplyDelete
  20. Many thanks for your tips.
    Kindly give me the code how can i create no. automatically?

    ReplyDelete
  21. hi rohan...
    i m making a project using netbeans IDE 7.1.2, database: MS Access.
    I face the problem in inserting data from the form to database table.. pls give some solution to it

    Natik

    ReplyDelete
  22. I have problem during below Statement

    st.executeUpdate("Insert into test_sst_player_master (ss_player_code, ss_player_name, ss_national_code, ss_sport_code, ss_fav_rating, sst_rating, ss_club1, ss_club2, ss_is_team) values('id','"+n1+"','"+c1+"','"+s1+"','"+fn1+"','"+rn1+"','"+cl1+"','"+cl2+"',"N")");

    ReplyDelete
    Replies
    1. and what is the problem?.....and why you have only single qoutes in id?

      Delete
  23. i need your help to complete my project.
    i'm currently working on a project in java and mysql as the backend.
    as a newbie to java am having some difficulty so i'll need your assistance to help complete the project

    ReplyDelete
  24. pls. can you help me with the java code to check login password and confirm login password on a login form?

    ReplyDelete
    Replies
    1. What problem are you facing?? any error??

      Delete
  25. hi, im trying to make a marble game with paddle but cant figure it out could you please assist me

    ReplyDelete
  26. -what is the problem, the error is cannot find symbol : methodshowMessageDialog?
    repy asap thanks

    ReplyDelete
  27. Can i use odbc connector instead of jdbc for mysql? many Thanks, im working on my project now. reply ASAP. thanks

    ReplyDelete
  28. hiii. when you used :String no = jTextField1.getText(); ..
    The attribute no is the one you used in your database?? Thanks

    ReplyDelete
    Replies
    1. You can name the variable anything. The order of columns in the sql query is what matters.

      Delete
  29. hey can u help me to find out what is the event handling of the button "submit", how it will work??????

    ReplyDelete
  30. plz can u tell me how to write the handling event to control the insertion of data....??????

    ReplyDelete
    Replies
    1. In Netbeans IDE, double click the submit button to enter it's actionPerformed event. Now follow step 4 and 5 for the coding.

      Delete
  31. data truncation:Data too long for column "no" at row1

    ReplyDelete
    Replies
    1. increase the size of your column 'no' in the database. You can achieve this through ALTER table command.

      Delete
  32. nice tutorial !!!! how do you update a table that refers the foreign key of a parent table and its rows?

    ReplyDelete
  33. plz can u tell me how to write the handling event to control the insertion of data.

    ReplyDelete
  34. hi rohan i create a connectivity with ms access and i have a error
    java.lang.null pointer so please say me what is will do for solw this error

    tank's

    ReplyDelete
  35. how can i get get values from database on sucessfully log in
    first log in into a form
    then i want the values from my database (back end)
    to coming form

    ReplyDelete