使用JDBC創(chuàng)建數(shù)據(jù)庫對象(5)

字號:

使用JDBC創(chuàng)建數(shù)據(jù)庫對象(5)
    · 構(gòu)建更高級別的JDBC對象
    從上面的例子可以明顯看出,如果可以將我們使用過的一些方法封裝在幾個更高級別對象中,那將非常有幫助,我們不僅可以封裝 try 程序塊,而且可以更簡單地訪問 ResultSet 方法。
    在這一部分中,我們將構(gòu)建一個新的 resultSet 對象,該對象封裝了JDBC ResultSet 對象,并以String數(shù)組的形式返回一行數(shù)據(jù)。我們發(fā)現(xiàn)您始終需要從 ResultSetMetaData 對象中獲取列的序號和名稱,因此,創(chuàng)建一個封裝元數(shù)據(jù)的新對象就非常合理。
    另外,我們經(jīng)常需要按名稱或整數(shù)索引提取某行的元素,如果不必總是將這些訪問語句包括 try 塊中,那將大有幫助。最后一點(diǎn),如果我們需要整行的內(nèi)容,則更方便的做法是將整行以String數(shù)組形式返回。在下面所示的 resultSet 對象中,我們致力于實(shí)現(xiàn)這些目標(biāo):
    class resultSet
    {
    //
    這個類是
    JDBC ResultSet
    對象的更高級抽象
    ResultSet rs;
    ResultSetMetaData rsmd;
    int numCols;
    public resultSet(ResultSet rset)
    {
    rs = rset;
    try
    {
    //
    同時獲取元數(shù)據(jù)和列數(shù)
    rsmd = rs.getMetaData();
    numCols = rsmd.getColumnCount();
    }
    catch (Exception e)
    {System.out.println("resultset error"
    +e.getMessage());}
    }
    //--
    public String[] getMetaData()
    {
    //
    返回包含所有列名或其他元數(shù)據(jù)的
    //
    一個數(shù)組
    String md[] = new String[numCols];
    try
    {
    for (int i=1; i<= numCols; i++)
    md[i-1] = rsmd.getColumnName(i);
    }
    catch (Exception e)
    {System.out.println("meta data error"+
    e.getMessage());}
    return md;
    }
    //--
    public boolean hasMoreElements()
    {
    try{
    return rs.next();
    }
    catch(Exception e){return false;}
    }
    //--
    public String[] nextElement()
    {
    //
    將行的內(nèi)容復(fù)制到字符串?dāng)?shù)組中
    String[] row = new String[numCols];
    try
    {
    for (int i = 1; i <= numCols; i++)
    row[i-1] = rs.getString(i);
    }
    catch (Exception e)
    {System.out.println("next element error"+
    e.getMessage());}
    return row;
    }
    //--
    public String getColumnValue(String columnName)
    {
    String res = "";
    try
    {
    res = rs.getString(columnName);
    }
    catch (Exception e)
    {System.out.println("Column value error:"+
    columnName+e.getMessage());}
    return res;
    }
    //--
    public String getColumnValue(int i)
    {
    String res = "";
    try
    {
    res = rs.getString(i);
    }
    catch (Exception e)
    {System.out.println("Column value error:"+
    columnName+e.getMessage());}
    return res;
    }
    //--
    public void finalize()
    {
    try{rs.close();}
    catch (Exception e)
    {System.out.println(e.getMessage());}
    }
    }
    通過簡單使用 new 操作符就地創(chuàng)建一個 ResultSet 對象,我們很容易將任何 ResultSet 對象封裝在此類中:
    ResultSet results = .. //
    按通常的方法獲得
    ResultsSet
    //
    利用它創(chuàng)建一個更有用的對象
    resultSet rs = new resultSet(results);
    并很容易在任何 JDBC 程序中使用這個對象。