从表中获取数据并在组合框中显示?

时间:2014-04-08 06:25:13

标签: java jdbc

Oracle Table ::

create table Appointment(App_ID number primary key,
Doctor_ID number,
Patient_ID number,
App_Date Date,
App_Time TIMESTAMP,
App_Charges number);

我将此作为我的GUI:2个按钮“插入”,“显示”

JComboBox combo_time, combo_charges;
JTextField text1, text2, text3, text4;
final String[] sTime = {
        "10:00", "10:15", "10:30", "10:45", "11:00", "11:15", "11:30", "11:45", 
        "12:00", "12:15", "12:30", "12:45", "13:00", "13:15", "13:30", "13:45", 
        "14:00", "14:15", "14:30", "14:45", "15:00", "15:15", "15:30", "15:45",   
};

final String[] sCharges = {
        "300", "500", "700", "900", "1100", "1300", "1500", 
};

for(int iCtr = 0; iCtr < sTime.length; iCtr++) {
    combo_time.addItem( sTime[iCtr] );
}

for(int iCtr = 0; iCtr < sCharges.length; iCtr++) {
    combo_charges.addItem( sCharges[iCtr] );
}

JDBC ::

if(e.getSource()==display) {
    try {
        //Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        //Connection      con = DriverManager.getConnection("jdbc:odbc:Employee");
        Class.forName("oracle.jdbc.OracleDriver");
        Connection        con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1522:xe", "hr", "hr");
        String            t1  = text1.getText();
        int               id  = Integer.parseInt(t1);
        PreparedStatement st  = con.prepareStatement("select * from appointment where App_ID=?");
        st.setInt(1,id);
        ResultSet         rs  = st.executeQuery();

        while(rs.next()) {
            text1.setText(t1);
            text2.setText(Integer.toString(rs.getInt(2)));
            text3.setText(Integer.toString(rs.getInt(3)));
            text4.setText(rs.getString(4));     
            combo_time.addItem(rs.getString("App_Time"));
            combo_charges.addItem(rs.getInt("App_Charges"));
        }
    }

现在我可以从表中获取数据但是我有一列Date而另一列Timestamp,我不知道如何获取它们并将其转换为String然后显示时间在组合框中(格式为hh:mm,但在表格中为Timestamp),日期在TextField。 虽然我尝试了上面的代码,但我得到了数据,但是组合框显示的是默认值,即组合框中的第一项。我想要的是在表格App_Time中显示combo_time值对于App_ID中的相应App_Chargescombo_charges值。 请帮忙 感谢

1 个答案:

答案 0 :(得分:0)

怎么样:

SimpleDateFormat myFormat = new SimpleDateFormat("HH:mm");

String text1 = myFormat.format(rs.getDate(index1));    
String text2 = myFormat.format(rs.getTimestamp(index2));