如何封裝查詢記錄到Java物件陣列
如何封裝查詢記錄到Java物件陣列
1:通過Vector的toArray()方法:
舉例如下:
(1)MySQL資料庫中建立一個職位表,其中只包含兩個欄位,職位ID,職位名稱, 建表語句如下:
CREATE TABLE POST ( POST_CODEintPRIMARY KEY , POST_NAMEvarchar(50)UNIQUE NOT NULL ) ; |
(2)
插入幾條測試記錄:略。
(3)
建立VO:
package publicclass PostRec { privateintpostCode ; private String postName ; public PostRec() { } public PostRec(int PostCode ,String postName){ this.postCode this.postName = postName ; } } publicint getPostCode() { returnpostCode; } publicvoid setPostCode(int postCode) { this.postCode = postCode; } public String getPostName() { returnpostName; } publicvoid setPostName(String postName) { this.postName = postName; } } |
(4)建立資料庫訪問類:
package org.mixih.db; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Vector; publicclass OprPost { String error; Connection con; public OprPost() { } publicvoid connect() throws ClassNotFoundException, SQLException, Exception { try { Class.forName("com.mysql.jdbc.Driver"); System.out.println("JDBC driver loaded"); con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/hrsys", "test", "test"); System.out.println("Database Connection established"); } catch (ClassNotFoundException e) { error = "Cound not locate DB driver"; thrownew ClassNotFoundException(error); } catch (SQLException e) { error = "SQLException : cound not connect to database."; thrownew SQLException(error); } catch (Exception e) { error = "Exception : an error occurred while connectingto database "; thrownew Exception(error); } } publicvoid disConnect() throws SQLException { try { if (con != null) { con.close(); } } catch (SQLException e) { error = "SQLExcepion : Unable to close the database connection."; thrownew SQLException(error); } } public PostRec[] viewPost() throws SQLException, Exception { ResultSet rs = null; Vector vForTemp = new Vector(); try { String queryString = "select * from post ;"; Statement stmt = con.createStatement(); rs = stmt.executeQuery(queryString); while(rs.next()){ int postCode = rs.getInt(1); String postName = rs.getString(2); PostRec postRec = new PostRec(postCode , postName ); vForTemp.add(postRec) ; } } catch (SQLException e) { error = " An exception occurred execute query ."; thrownew SQLException(error); } catch (Exception e) { error = "Aneception occurred while while retriving books."; thrownew Exception(error); } return (PostRec[])vForTemp.toArray( new PostRec[0]); } publicstaticvoid main(String[] args) throws Exception { OprPost myOprPost = new OprPost(); myOprPost.connect(); PostRec[] postRecs = myOprPost.viewPost(); for(int i = 0 ; i < postRecs.length ; i++ ) { System.out.println(postRecs[i].getPostCode()); System.out.println(postRecs[i].getPostName()); } myOprPost.disConnect(); } } |