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

📄 statement.java

📁 基于b/s的网上书店
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
/*
   Copyright (C) 2002 MySQL AB

      This program is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published by
      the Free Software Foundation; either version 2 of the License, or
      (at your option) any later version.

      This program is distributed in the hope that it will be useful,
      but WITHOUT ANY WARRANTY; without even the implied warranty of
      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      GNU General Public License for more details.

      You should have received a copy of the GNU General Public License
      along with this program; if not, write to the Free Software
      Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

 */
package com.mysql.jdbc;

import java.io.UnsupportedEncodingException;

import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Types;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


/**
 * A Statement object is used for executing a static SQL statement and
 * obtaining the results produced by it.
 * 
 * <p>
 * Only one ResultSet per Statement can be open at any point in time.
 * Therefore, if the reading of one ResultSet is interleaved with the reading
 * of another, each must have been generated by different Statements.  All
 * statement execute methods implicitly close a statement's current ResultSet
 * if an open one exists.
 * </p>
 *
 * @author Mark Matthews
 * @version $Id: Statement.java,v 1.20.2.17 2004/02/13 22:31:25 mmatthew Exp $
 *
 * @see java.sql.Statement
 * @see ResultSet
 */
public class Statement implements java.sql.Statement {
    /** The connection that created us */
    protected Connection connection = null;

    /** Holds batched commands */
    protected List batchedArgs;

    /** List of currently-open ResultSets */
    protected List openResults = new ArrayList();

    /** The next result set */
    protected ResultSet nextResults = null;

    /** The current results */
    protected ResultSet results = null;

    /** The warnings chain. */
    protected SQLWarning warningChain = null;
    
    /** The pending warnings chain */
    protected SQLWarning pendingWarnings = null;

    /** The character converter to use (if available) */
    protected SingleByteCharsetConverter charConverter = null;

    /** The character encoding to use (if available) */
    protected String charEncoding = null;

    /** The catalog in use */
    protected String currentCatalog = null;

    /** Should we process escape codes? */
    protected boolean doEscapeProcessing = true;

    /** Has this statement been closed? */
    protected boolean isClosed = false;

    /** Has someone changed this for this statement? */
    protected boolean maxRowsChanged = false;

    /** Are we in pedantic mode? */
    protected boolean pedantic = false;

    /** The max field size for this statement */
    protected int maxFieldSize = MysqlIO.getMaxBuf();

    /**
     * The maximum number of rows to return for this statement (-1 means _all_
     * rows)
     */
    protected int maxRows = -1;

    /** The concurrency for this result set (updatable or not) */
    protected int resultSetConcurrency = 0;

    /** The type of this result set (scroll sensitive or in-sensitive) */
    protected int resultSetType = 0;

    /** The timeout for a query */
    protected int timeout = 0;

    /** The auto_increment value for the last insert */
    protected long lastInsertId = -1;

    /** The update count for this statement */
    protected long updateCount = -1;

    /** The number of rows to fetch at a time (currently ignored) */
    private int fetchSize = 0;

    /** Does the server support CAST/CONVERT? */
    private boolean serverSupportsConvertFn;
    
    /**
     * Constructor for a Statement.
     *
     * @param c the Connection instantation that creates us
     * @param catalog the database name in use when we were created
     *
     * @throws SQLException if an error occurs.
     */
    public Statement(Connection c, String catalog) throws SQLException {
        if (Driver.TRACE) {
            Object[] args = { c };
            Debug.methodCall(this, "constructor", args);
        }

        if ((c == null) || ((com.mysql.jdbc.Connection) c).isClosed()) {
            throw new SQLException("Connection is closed.", "08003");
        }

        this.connection = c;
        this.currentCatalog = catalog;
        this.pedantic = this.connection.isPedantic();
        this.serverSupportsConvertFn = this.connection.getIO().versionMeetsMinimum(4, 0, 2);

        //
        // Adjust, if we know it
        //
        if (connection != null) {
            maxFieldSize = connection.getMaxAllowedPacket();
        }

        if (this.connection.useUnicode()) {
            this.charEncoding = connection.getEncoding();
            this.charConverter = this.connection.getCharsetConverter(this.charEncoding); 
        }
        
        int maxRowsConn = this.connection.getMaxRows();
        
        if (maxRowsConn != -1) {
        	setMaxRows(maxRowsConn);
        }
    }

    /**
     * JDBC 2.0  Return the Connection that produced the Statement.
     *
     * @return the Connection that produced the Statement
     *
     * @throws SQLException if an error occurs
     */
    public java.sql.Connection getConnection() throws SQLException {
        return (java.sql.Connection) connection;
    }

    /**
     * setCursorName defines the SQL cursor name that will be used by
     * subsequent execute methods.  This name can then be used in SQL
     * positioned update/delete statements to identify the current row in the
     * ResultSet generated by this statement.  If a database doesn't support
     * positioned update/delete, this method is a no-op.
     * 
     * <p>
     * <b>Note:</b> This MySQL driver does not support cursors.
     * </p>
     *
     * @param name the new cursor name
     *
     * @exception java.sql.SQLException if a database access error occurs
     */
    public void setCursorName(String name) throws java.sql.SQLException {
        if (Driver.TRACE) {
            Object[] args = { name };
            Debug.methodCall(this, "setCursorName", args);
        }

        // No-op
    }

    /**
     * If escape scanning is on (the default), the driver will do escape
     * substitution before sending the SQL to the database.
     *
     * @param enable true to enable; false to disable
     *
     * @exception java.sql.SQLException if a database access error occurs
     */
    public void setEscapeProcessing(boolean enable)
        throws java.sql.SQLException {
        if (Driver.TRACE) {
            Object[] args = { new Boolean(enable) };
            Debug.methodCall(this, "setEscapeProcessing", args);
        }

        doEscapeProcessing = enable;
    }

    //--------------------------JDBC 2.0-----------------------------

    /**
     * JDBC 2.0 Give a hint as to the direction in which the rows in a result
     * set will be processed. The hint applies only to result sets created
     * using this Statement object.  The default value is
     * ResultSet.FETCH_FORWARD.
     *
     * @param direction the initial direction for processing rows
     *
     * @exception SQLException if a database-access error occurs or direction
     *            is not one of ResultSet.FETCH_FORWARD,
     *            ResultSet.FETCH_REVERSE, or ResultSet.FETCH_UNKNOWN
     */
    public void setFetchDirection(int direction) throws SQLException {
        switch (direction) {
        case java.sql.ResultSet.FETCH_FORWARD:
        case java.sql.ResultSet.FETCH_REVERSE:
        case java.sql.ResultSet.FETCH_UNKNOWN:
            break;

        default:
            throw new SQLException("Illegal value for setFetchDirection()",
                SQLError.SQL_STATE_ILLEGAL_ARGUMENT);
        }
    }

    /**
     * JDBC 2.0 Determine the fetch direction.
     *
     * @return the default fetch direction
     *
     * @exception SQLException if a database-access error occurs
     */
    public int getFetchDirection() throws SQLException {
        return java.sql.ResultSet.FETCH_FORWARD;
    }

    /**
     * JDBC 2.0 Give the JDBC driver a hint as to the number of rows that
     * should  be fetched from the database when more rows are needed.  The
     * number  of rows specified only affects result sets created using this
     * statement. If the value specified is zero, then the hint is ignored.
     * The default value is zero.
     *
     * @param rows the number of rows to fetch
     *
     * @exception SQLException if a database-access error occurs, or the
     *            condition 0 &lt;= rows &lt;= this.getMaxRows() is not
     *            satisfied.
     */
    public void setFetchSize(int rows) throws SQLException {
        if (((rows < 0) && (rows != Integer.MIN_VALUE))
                || ((maxRows != 0) && (maxRows != -1)
                && (rows > this.getMaxRows()))) {
            throw new SQLException("Illegal value for setFetchSize()", SQLError.SQL_STATE_ILLEGAL_ARGUMENT);
        }

        fetchSize = rows;
    }

    /**
     * JDBC 2.0 Determine the default fetch size.
     *
     * @return the number of rows to fetch at a time
     *
     * @throws SQLException if an error occurs
     */
    public int getFetchSize() throws SQLException {
        return fetchSize;
    }

    /**
     * DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     *
     * @throws SQLException DOCUMENT ME!
     */
    public java.sql.ResultSet getGeneratedKeys() throws SQLException {
        Field[] fields = new Field[1];
        fields[0] = new Field("", "GENERATED_KEY", Types.BIGINT, 17);

        ArrayList rowSet = new ArrayList();

        long beginAt = getLastInsertID();
        int numKeys = getUpdateCount();

        String serverInfo = this.results.getServerInfo();

		// 
		// Only parse server info messages for 'REPLACE'
		// queries
		//
		
        if ((numKeys > 0) 
        		&& this.results.getFirstCharOfQuery() == 'R'
        		&& (serverInfo != null)
                && (serverInfo.length() > 0)) {
            numKeys = getRecordCountFromInfo(serverInfo);
        }

        if ((beginAt > 0) && (numKeys > 0)) {
            for (int i = 0; i < numKeys; i++) {
                byte[][] row = new byte[1][];
                row[0] = Long.toString(beginAt++).getBytes();
                rowSet.add(row);
            }
        }

        return new com.mysql.jdbc.ResultSet(currentCatalog, fields,
            new RowDataStatic(rowSet), connection);
    }

    /**
     * getLastInsertID returns the value of the auto_incremented key after an
     * executeQuery() or excute() call.
     * 
     * <p>
     * This gets around the un-threadsafe behavior of "select LAST_INSERT_ID()"
     * which is tied to the Connection that created this Statement, and
     * therefore could have had many INSERTS performed before one gets a
     * chance to call "select LAST_INSERT_ID()".
     * </p>
     *
     * @return the last update ID.
     */
    public long getLastInsertID() {
        if (Driver.TRACE) {
            Object[] args = new Object[0];
            Debug.methodCall(this, "getLastInsertID", args);
        }

        return lastInsertId;
    }

    /**
     * getLongUpdateCount returns the current result as an update count, if the
     * result is a ResultSet or there are no more results, -1 is returned.  It
     * should only be called once per result.
     * 
     * <p>
     * This method returns longs as MySQL server versions newer than  3.22.4
     * return 64-bit values for update counts
     * </p>
     *
     * @return the current update count.
     */
    public long getLongUpdateCount() {
        if (Driver.TRACE) {
            Object[] args = new Object[0];
            Debug.methodCall(this, "getLongUpdateCount", args);
        }

        if (results == null) {
            return -1;
        }

        if (results.reallyResult()) {
            return -1;
        }

⌨️ 快捷键说明

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