資源描述:
《Java的Jtable、從數(shù)據(jù)庫取數(shù)據(jù)顯示在表格中》由會員上傳分享,免費在線閱讀,更多相關(guān)內(nèi)容在行業(yè)資料-天天文庫。
1、數(shù)據(jù)庫操作代碼://?Load?JDBC?driver??Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");????String?dbUrl?=?"jdbc:odbc:driver={Microsoft?Access?Driver?(*.mdb)};DBQ=access\test.mdb";??Connection?con?=?DriverManager.getConnection(dbUrl,?"","");??Statement?state?=?con.createStatemen(ResultSet.TYPE_SCROLL_SENSITIV
2、E,??????????????????????????????????????ResultSet.CONCUR_UPDATABLE);??//?執(zhí)行SQL語句??String?sql?=?"select?*?from?score";??ResultSet?rs?=?state.executeQuery(sql);??displayResultSet(rs);??rs.close();??state.close();??con.close();?將數(shù)據(jù)顯示在表格中:?????private?void?displayResultSet(ResultSet?rs)?throws?SQLExce
3、ption?{????????boolean?moreRecords?=?rs.next();?//?定位到達第一條記錄????????if?(!moreRecords)?{????????????JOptionPane.showMessageDialog(null,?"結(jié)果集中無記錄",?"無記錄",????????????????????JOptionPane.INFORMATION_MESSAGE);????????????return;????????}????????Vector?rows?=?new?Vector();????????Vector?columnHeads?=?n
4、ew?Vector();????????try?{????????????ResultSetMetaData?rsmd?=?rs.getMetaData();?//?獲得rs結(jié)果集中列屬性信息????????????for?(int?i?=?1;?i?<=?rsmd.getColumnCount();?++i)????????????????columnHeads.addElement(rsmd.getColumnName(i));?//?獲得列名(將列名存放至向量columnHeads)????????????do?{????????????????rows.addElement(get
5、NextRow(rs,?rsmd));????????????}?????????????while?(rs.next());?//?利用循環(huán)獲得所有記錄????????????jTable?=?new?JTable(rows,?columnHeads);?//?將獲得的行列數(shù)據(jù)信息作為參數(shù)重新構(gòu)造表格視圖????????????jTable.setSize(new?Dimension(383,?81));????????????JScrollPane?scroller?=?new?JScrollPane(jTable);//?創(chuàng)建帶有滾動條的面板,并將表格視圖加入????????????
6、Container?c?=?getContentPane();?//?獲取溶器????????????//?c.remove(2);?//????????????//?從溶器中移除指定控件(本窗體中有二級面板有兩個,第一個存放文本域及按鈕,第二個存放表格視圖,故移除1)????????????c.add(scroller,?BorderLayout.CENTER);?//?將面板重新加入溶器中????????????c.validate();?//?驗證此容器及其所有子組件????????}?catch?(SQLException?e)?{????????????e.printStackT
7、race();????????}????}????????private?Vector?getNextRow(ResultSet?rs,?ResultSetMetaData?rsmd)????????????throws?SQLException?{????????Vector?currentRow?=?new?Vector();?//?定義一個向量,用于存放記錄????????for?(int?i?=?1;?i?<=?