2012-09-24 48 views
2

從我是否嘗試過如何從一個Oracle數據庫來的JComboBox負荷值,使之更容易爲用戶選擇這樣的:加載數據庫字段值的JComboBox

Connection dbcon = null; 
    try { 
     Class.forName("oracle.jdbc.driver.OracleDriver"); 
     dbcon = DriverManager.getConnection(" 
      jdbc:oracle:thin:@localhost:1521:XE", "USERNAME", "PASSWORD"); 
     Statement st = dbcon.createStatement(); 
     String combo = "Select EMP_IDNUM from employees"; 
     ResultSet res = st.executeQuery(combo); 
     while(res.next()){ 
      String ids = res.getString("EMP_IDNUM"); 
      String [] str = new String[]{ids}; 
      cboId = new JComboBox(str); 
     } 
    } catch (Exception d) { 
     System.out.println(d); 
    } 

這只是讓我第一值放入JComboBox cboID。將整個字段數據(EMP_IDNUM)加載到Jcombobox中的最佳方法是什麼?

+0

我無法相信有人是「足夠好」 DOwnvote我的問題Whle我只是Askng .. – ErrorNotFoundException

回答

2
String [] str = new String[]{ids}; 

這意味着你的字符串數組只有一個您已加載的ID值String ids = res.getString("EMP_IDNUM");

if(rs.getRow()>0){ 
String [] str = new String[res.getRow()]; 
int i=0; 
while(res.next()){ 
    str[i++] = res.getString("EMP_IDNUM"); 
} 
} 
JComboBox jcb = new JComboBox(str); 

除了數組,您還可以使用Vector來創建JComboBox。

2

有三個重要領域

a)緊靠在finally block所有JDBC Objects,因爲這些Object都沒有,從來沒有GC'ed

try { 

} catch (Exception d) { 
    System.out.println(d); 
} finally { 
    try { 
     st.close() 
     res.close() 
     dbcon.close() 
    } catch (Exception d) { 
     //not important 
    } 
} 

二)沒有創建任何Objectstry - catch - finally,準備之前

含義cboId = new JComboBox(str);

三)把所有的數據從JDBC到ComboBoxModel,準備在此之前