⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 tdsresultset.java

📁 Java写的TDS协议(JDBC/ODBC)实现
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
//
// Copyright 1998, 1999 CDS Networks, Inc., Medford Oregon
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
// 3. All advertising materials mentioning features or use of this software
//    must display the following acknowledgement:
//      This product includes software developed by CDS Networks, Inc.
// 4. The name of CDS Networks, Inc.  may not be used to endorse or promote
//    products derived from this software without specific prior
//    written permission.
//
// THIS SOFTWARE IS PROVIDED BY CDS NETWORKS, INC. ``AS IS'' AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED.  IN NO EVENT SHALL CDS NETWORKS, INC. BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
//


package net.sourceforge.jtds.jdbc;

import java.sql.*;

/**
 *  <P>
 *
 *  A ResultSet provides access to a table of data generated by executing a
 *  Statement. The table rows are retrieved in sequence. Within a row its column
 *  values can be accessed in any order. <P>
 *
 *  A ResultSet maintains a cursor pointing to its current row of data.
 *  Initially the cursor is positioned before the first row. The 'next' method
 *  moves the cursor to the next row. <P>
 *
 *  The getXXX methods retrieve column values for the current row. You can
 *  retrieve values either using the index number of the column, or by using the
 *  name of the column. In general using the column index will be more
 *  efficient. Columns are numbered from 1. <P>
 *
 *  For maximum portability, ResultSet columns within each row should be read in
 *  left-to-right order and each column should be read only once. <P>
 *
 *  For the getXXX methods, the JDBC driver attempts to convert the underlying
 *  data to the specified Java type and returns a suitable Java value. See the
 *  JDBC specification for allowable mappings from SQL types to Java types with
 *  the ResultSet.getXXX methods. <P>
 *
 *  Column names used as input to getXXX methods are case insensitive. When
 *  performing a getXXX using a column name, if several columns have the same
 *  name, then the value of the first matching column will be returned. The
 *  column name option is designed to be used when column names are used in the
 *  SQL query. For columns that are NOT explicitly named in the query, it is
 *  best to use column numbers. If column names were used there is no way for
 *  the programmer to guarantee that they actually refer to the intended
 *  columns. <P>
 *
 *  A ResultSet is automatically closed by the Statement that generated it when
 *  that Statement is closed, re-executed, or is used to retrieve the next
 *  result from a sequence of multiple results. <P>
 *
 *  The number, types and properties of a ResultSet's columns are provided by
 *  the ResulSetMetaData object returned by the getMetaData method.
 *
 *@author     Craig Spannring
 *@author     Alin Sinpalean
 *@author     The FreeTDS project
 *@created    17 March 2001
 *@version    $Id: TdsResultSet.java,v 1.3 2002/11/11 15:22:42 alin_sinpalean Exp $
 *@see        Statement#executeQuery
 *@see        Statement#getResultSet
 *@see        ResultSetMetaData @
 *@see        Tds#getRow
 */
public class TdsResultSet extends AbstractResultSet implements ResultSet
{
    Tds tds = null;
    TdsStatement stmt = null;

    Context context = null;

    int row = 0;
    boolean hitEndOfData = false;
    boolean isClosed = false;

    int rowIndex = -1;
    int rowCount = 0;
    PacketRowResult[] rowCache = null;

    /**
     *  Description of the Field
     */
    public final static String cvsVersion = "$Id: TdsResultSet.java,v 1.3 2002/11/11 15:22:42 alin_sinpalean Exp $";

    public TdsResultSet(Tds tds_, TdsStatement stmt_, SQLWarningChain stmtChain, int fetchSize) throws SQLException
    {
        tds = tds_;
        stmt = stmt_;
        warningChain = new SQLWarningChain();
        hitEndOfData = false;
        rowCache = new PacketRowResult[this.fetchSize];

        if( fetchSize > 0 )
            this.fetchSize = fetchSize;

        startResultSet(tds, stmtChain);
    }

    private void startResultSet(Tds tds, SQLWarningChain stmtWarningChain) throws SQLException
    {
        Columns names = null;
        Columns info  = null;

        try
        {
            while( !tds.isResultRow() && !tds.isEndOfResults() )
            {
                PacketResult tmp = tds.processSubPacket();

                if( tmp instanceof PacketColumnNamesResult )
                    names = ((PacketColumnNamesResult)tmp).getColumnNames();
                else if( tmp instanceof PacketColumnInfoResult )
                    info = ((PacketColumnInfoResult)tmp).getColumnInfo();
                else if( tmp instanceof PacketMsgResult )
                    stmtWarningChain.addOrReturn((PacketMsgResult)tmp);
                else if( tmp instanceof PacketColumnOrderResult )
                {
                    // XXX ORDER BY columns
                }
                else if( tmp instanceof PacketTabNameResult )
                {
                    // XXX Names of tables from which we got the results
                }
                else if( tmp instanceof PacketControlResult )
                {
                    // XXX Controlrow information
                }
                else if( tmp instanceof PacketUnknown )
                {
                    // XXX Need to add to the warning chain
                }
                else
                {
                    stmtWarningChain.addException(new SQLException("Trying to get a ResultSet. Found a "
                        + tmp.getClass().getName()));
                    break;
                }
            }

            stmtWarningChain.checkForExceptions();

            // TDS 7.0 includes everything in one subpacket.
            if( info != null )
                names.merge(info);

            context = new Context(names, tds.getEncoder());
        }
        catch( net.sourceforge.jtds.jdbc.TdsException e )
        {
            stmtWarningChain.addException(new SQLException(e.getMessage()));
        }
        catch( java.io.IOException e)
        {
            stmtWarningChain.addException(new SQLException(e.getMessage()));
        }

        stmtWarningChain.checkForExceptions();
    }

    public Context getContext()
    {
        return context;
    }

    /**
     *  JDBC 2.0 Gives a hint as to the direction in which the rows in this
     *  result set will be processed. The initial value is determined by the
     *  statement that produced the result set. The fetch direction may be
     *  changed at any time.
     *
     *@param  direction         The new FetchDirection value
     *@exception  SQLException  if a database access error occurs or the result
     *      set type is TYPE_FORWARD_ONLY and the fetch direction is not
     *      FETCH_FORWARD.
     */
    public void setFetchDirection(int direction) throws SQLException
    {
        checkClosed();
        if( direction != FETCH_FORWARD )
            throw new SQLException(
                "The result set type is TYPE_FORWARD_ONLY and the fetch direction is not FETCH_FORWARD.");
    }

    /**
     *  JDBC 2.0 Gives the JDBC driver a hint as to the number of rows that
     *  should be fetched from the database when more rows are needed for this
     *  result set. If the fetch size specified is zero, the JDBC driver ignores
     *  the value and is free to make its own best guess as to what the fetch
     *  size should be. The default value is set by the statement that created
     *  the result set. The fetch size may be changed at any time.
     *
     *@param  rows              the number of rows to fetch
     *@exception  SQLException  if a database access error occurs or the
     *      condition 0 <= rows <= this.getMaxRows() is not satisfied.
     */
    public synchronized void setFetchSize(int rows) throws SQLException
    {
        checkClosed();
        int maxRows = stmt.getMaxRows();

        if( rows<0 || (maxRows>0 && rows>maxRows) )
            throw new SQLException("Illegal fetch size: "+rows);

        // If the user lets us choose, we'll use the whole cache
        if( rows == 0 )
        {
            fetchSize = rowCache.length;
            return;
        }

        // Reallocate the cache if too small
        if( rows > rowCache.length )
        {
            PacketRowResult[] newCache = new PacketRowResult[rows];
            System.arraycopy(rowCache, 0, newCache, 0, rowCache.length);
            rowCache = newCache;
        }

        fetchSize = rows;
    }

    /**
     *  Get the name of the SQL cursor used by this ResultSet. <P>
     *
     *  In SQL, a result table is retrieved through a cursor that is named. The
     *  current row of a result can be updated or deleted using a positioned
     *  update/delete statement that references the cursor name. <P>
     *
     *  JDBC supports this SQL feature by providing the name of the SQL cursor
     *  used by a ResultSet. The current row of a ResultSet is also the current
     *  row of this SQL cursor. <P>
     *
     *  <B>Note:</B> If positioned update is not supported a SQLException is
     *  thrown
     *
     *@return                   the ResultSet's SQL cursor name
     *@exception  SQLException  if a database-access error occurs.
     */
    public String getCursorName() throws SQLException
    {
        throw new SQLException("Not implemented (getCursorName)");
    }

    public SQLWarning getWarnings() throws SQLException
    {
        checkClosed();
        return warningChain.getWarnings();
    }

    //---------------------------------------------------------------------
    // Traversal/Positioning
    //---------------------------------------------------------------------

    /**
     *  JDBC 2.0 <p>
     *
     *  Indicates whether the cursor is before the first row in the result set.
     *
     *@return                   true if the cursor is before the first row,
     *      false otherwise. Returns false when the result set contains no rows.
     *@exception  SQLException  if a database access error occurs
     */
    public synchronized boolean isBeforeFirst() throws SQLException
    {
        checkClosed();
        return row==0 && haveMoreResults();
    }

    /**
     *  JDBC 2.0 <p>
     *
     *  Indicates whether the cursor is after the last row in the result set.
     *
     *@return                   true if the cursor is after the last row, false
     *      otherwise. Returns false when the result set contains no rows.
     *@exception  SQLException  if a database access error occurs
     */
    public boolean isAfterLast() throws SQLException
    {
        checkClosed();
        return hitEndOfData;
    }

    /**
     *  JDBC 2.0 <p>
     *
     *  Indicates whether the cursor is on the first row of the result set.
     *
     *@return                   true if the cursor is on the first row, false
     *      otherwise.
     *@exception  SQLException  if a database access error occurs
     */
    public boolean isFirst() throws SQLException
    {

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -