Load data from MySQL database to Combo box Using Java

0
81

This tutorial is all about load data from MySQL database to Combo box using Java. This tutorial will teach you on how your programs load a specific row of data from MySQL database into your combo box element.

It is important that you add this feature to your program because there are some instances that your combo box display a list of information depending on the database data. This program used jCombobox and jLabel to make this tutorial successful. Please follow all the steps below to complete this tutorial.

Load data from MySQL database to Combo box in Java Steps

  1. Add/Create a new Form inside your java projects. In my case, I named my form using “LoadDataInCombobox”.

2. Design your form just look like the image below. All of the elements are located in your Netbeans tool pallets.

3. Copy the codes below and paste it into your program. The following codes are used in accessing the required libraries needed in this program.

  1. import java.sql.Connection;
  2. import java.sql.PreparedStatement;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import javax.swing.JOptionPane;

4. Create a new Method inside your class. In my case, I used “loadUserName” as my method name.

  1. public final void loadUserName(){
  2.  
  3. }

5. Insert the following codes below inside your new create method. The codes compose of MySQL statements needed in accessing the MySQL database.

  1. try {
  2. String sql="SELECT * FROM userinfo";
  3. pst=conn.prepareStatement(sql);
  4. rs = pst.executeQuery(sql);
  5. while(rs.next()){
  6. String fname = rs.getString("FirstName");
  7. String lname = rs.getString("LastName");
  8. String name = fname + " " + lname;
  9. jComboBox1.addItem(name);
  10. }
  11. }catch(SQLException e) {
  12. JOptionPane.showMessageDialog(this, e.getMessage());
  13. }

6. Copy the name of your method and insert it inside your public method together with the “initComponents”. When the program is running, all of the statement inside the public class method will executed.

  1. public LoadDataInCombobox() {
  2. initComponents();
  3. conn = dbConnection.MyDbConnection();
  4. loadUserName();
  5. }

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

After completing this tutorial, you are now learned and understand on how to load a specific data from MySQL database using your Netbeans Ide and Java programming language. All of the source codes are tested in Netbeans IDE 8.0.1, JDK 8.0, and MySQL 5.0 and up database. If you have question and suggestion regarding my tutorial, feel free to contact me at [email protected] or you can use the contact details displayed in this website.

Related Articles You May Like:

Facebook Comments
(Visited 82 times, 1 visits today)

LEAVE A REPLY

Please enter your comment!
Please enter your name here