Save Data to MySQL in Java using Netbeans

0
79

This tutorial entitled “Save Data to MySQL in Java using Netbeans” will help you to understand on how you can create a program that can save data to MySQL database using Java. Before we start, be sure that you understand on how to create a MySQL schema, entity, and attribute.

Create a new schema and entity and named it what you want. Create the following attribute in your entity. Add FirstName, LastName, Address, Contact, and Email in your entity/table. The data types must set to “VarChar” so that it can accept multiple types of user input. This program uses jToolbar, jLabel, jPanel, jTextField, and jButton to create the UI of the program.

Save Data to MySQL using Java Steps

  1. Create/Add a new JFrame form.

2. Design your JFrame just look like the image below. Just download the icon from the internet for save button. Be sure to rename the entire element added in your form.

3. Double click your button and add the following codes below. Our codes uses try catch exception and jOptionPane for user notification.

  1. try{
  2. String str="INSERT INTO userinfo "
  3. + "(FirstName,LastName,Address,Contact,Email) "
  4. + "VALUES(?,?,?,?,?)";
  5. pst=conn.prepareStatement(str);
  6. pst.setString(1, jTextField1.getText());
  7. pst.setString(2, jTextField2.getText());
  8. pst.setString(3, jTextField3.getText());
  9. pst.setString(4, jTextField4.getText());
  10. pst.setString(5, jTextField5.getText());
  11. pst.execute();
  12. JOptionPane.showMessageDialog(null,"Successfully Save!");
  13. }
  14. catch (HeadlessException | SQLException e){
  15. JOptionPane.showMessageDialog(this, e.getMessage());
  16. }

4. Run your program and the output should look like the image below.

5. After hitting the button, a dialog box appears saying that the data is added into database.

Related Articles You May Like:

Facebook Comments
(Visited 88 times, 1 visits today)

LEAVE A REPLY

Please enter your comment!
Please enter your name here