Thursday, 17 June 2021

How can I get data from database table into combo box in Java

How can I get data in a combo box from a database in Java | Load data from database to Combo box in Java:

In this we will see how to load data from database table into combo box component of swings in java.  

 package demo;
 

import java.awt.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.util.Vector;
import javax.swing.*;
public class RuntimeComboBoxDemo {
 
   
   public static void main(String[] args) {

      
       try{  


            Class.forName("oracle.jdbc.driver.OracleDriver");  
            Connection con=DriverManager.getConnection(  
                            "jdbc:oracle:thin:@localhost:1521:xe","system","system");  
            System.out.println("Connected to database...");
            Statement pstmt=con.createStatement();
            ResultSet rs=pstmt.executeQuery("select distinct ename from emp"); 
       
               JFrame f=new JFrame();
               Vector<String> v=new Vector<String>();
               while(rs.next()){
                  v.add(rs.getString(1));
               }
              JComboBox jcb = new JComboBox(v);
              f.setLayout(new FlowLayout());
              f.add(jcb);
              f.setSize(300, 250);
              f.setLocationRelativeTo(null);
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              f.setVisible(true);
              }
    catch(Exception e){
        System.out.println(e);
    }
   }
    
}

 

 


No comments:

Post a Comment