如何封装查询记录到Java对象数组
1:通过Vector的toArray()方法:
举例如下:
(1)MySQL数据库中创建一个职位表,其中只包含两个字段,职位ID,职位名称, 建表语句如下:
CREATE TABLE POST ( POST_CODE int PRIMARY KEY , POST_NAME varchar(50) UNIQUE NOT NULL ) ; |
(2)
插入几条测试记录:略。
(3)
创建VO:
package org.mixih.db;
public class PostRec {
private int postCode ; private String postName ;
public PostRec() { }
public PostRec(int PostCode ,String postName){ this.postCode = postCode ; this.postName = postName ; }
}
public int getPostCode() { return postCode; }
public void setPostCode(int postCode) { this.postCode = postCode; }
public String getPostName() { return postName; }
public void 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;
public class OprPost {
String error;
Connection con;
public OprPost() { }
public void 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";
throw new ClassNotFoundException(error);
} catch (SQLException e) {
error = "SQLException : cound not connect to database.";
throw new SQLException(error);
} catch (Exception e) {
error = "Exception : an error occurred while connecting to database ";
throw new Exception(error); } }
public void disConnect() throws SQLException { try { if (con != null) {
con.close();
} } catch (SQLException e) {
error = "SQLExcepion : Unable to close the database connection.";
throw new 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 .";
throw new SQLException(error);
} catch (Exception e) {
error = "Aneception occurred while while retriving books.";
throw new Exception(error); } return (PostRec[])vForTemp.toArray( new PostRec[0]); }
public static void 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(); } }
|