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

📄 connection.java

📁 SSD9 练习9
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/* * MM JDBC Drivers for MySQL * * $Id: Connection.java,v 1.2 1998/08/25 00:53:46 mmatthew Exp $ * * Copyright (C) 1998 Mark Matthews <mmatthew@worldserver.com> *  * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Library General Public License for more details. *  * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA  02111-1307, USA. * * See the COPYING file located in the top-level-directory of * the archive of this library for complete text of license. * * Some portions: * * Copyright (c) 1996 Bradley McLean / Jeffrey Medeiros * Modifications Copyright (c) 1996/1997 Martin Rode * Copyright (c) 1997 Peter T Mount *//** * A Connection represents a session with a specific database.  Within the * context of a Connection, SQL statements are executed and results are * returned. * * <P>A Connection's database is able to provide information describing * its tables, its supported SQL grammar, its stored procedures, the * capabilities of this connection, etc.  This information is obtained * with the getMetaData method. * * <p><B>Note:</B> MySQL does not support transactions, so all queries *                 are committed as they are executed. * * @see java.sql.Connection * @author Mark Matthews <mmatthew@worldserver.com> * @version $Id$ */package org.gjt.mm.mysql;import java.io.UnsupportedEncodingException;import java.sql.*;import java.util.Properties;public class Connection implements java.sql.Connection{    MysqlIO _IO                 = null;    private boolean _isClosed   = true;        private String  _Host       = null;    private int     _port       = 3306;    private String  _User       = null;    private String  _Password   = null;    private String  _Database   = null;        private boolean _autoCommit = true;    private boolean _readOnly   = false;    private boolean _do_unicode = false;    private String  _Encoding   = null;        private String  _MyURL      = null;    private int     _max_rows   = -1;    private boolean _max_rows_changed = false;    private org.gjt.mm.mysql.Driver _MyDriver;    //    // This is for the high availability :) routines     //    private boolean _high_availability = false;    private int     _max_reconnects    = 3;    private double  _initial_timeout   = 2.0D;        // The command used to "ping" the database.    // Newer versions of MySQL server have a ping() command,    // but this works for everything.    private static final String _PING_COMMAND = "SELECT 1";    /**     * Connect to a MySQL Server.     *     * <p><b>Important Notice</b>     *     * <br>Although this will connect to the database, user code should open     * the connection via the DriverManager.getConnection() methods only.     *     * <br>This should only be called from the org.gjt.mm.mysql.Driver class.     *     * @param Host the hostname of the database server     * @param port the port number the server is listening on     * @param Info a Properties[] list holding the user and password     * @param Database the database to connect to     * @param Url the URL of the connection     * @param D the Driver instantation of the connection     * @return a valid connection profile     * @exception java.sql.SQLException if a database access error occurs     */  public Connection(String Host, int port, Properties Info, String Database,                     String Url, Driver D) throws java.sql.SQLException  {      if (Driver.trace) {	  Object[] Args = {Host, new Integer(port), Info,			   Database, Url, D};	  Debug.methodCall(this, "constructor", Args);      }      if (Host == null) {	  _Host = "localhost";      }      else {	  _Host = new String(Host);      }            _port = port;            if (Database == null) {	  throw new SQLException("Malformed URL '" + Url + "'.", "S1000");      }      _Database = new String(Database);            _MyURL = new String(Url);      _MyDriver = D;            String U = Info.getProperty("user");      String P = Info.getProperty("password");            if (U == null || U.equals(""))	  _User = "nobody";      else	  _User = new String(U);            if (P == null)	  _Password = "";      else	  _Password = new String(P);            // Check for driver specific properties            if (Info.getProperty("autoReconnect") != null) {	  _high_availability = Info.getProperty("autoReconnect").toUpperCase().equals("TRUE");      }            if (_high_availability) {	  if (Info.getProperty("maxReconnects") != null) {	      try {		  int n = Integer.parseInt(Info.getProperty("maxReconnects"));		  _max_reconnects = n;	      }	      catch (NumberFormatException NFE) {		  throw new SQLException("Illegal parameter '" + 					 Info.getProperty("maxReconnects") 					 +"' for maxReconnects", "0S100");	      }	  }	  	  if (Info.getProperty("initialTimeout") != null) {	      try {		  double n = Integer.parseInt(Info.getProperty("intialTimeout"));		  _initial_timeout = n;	      }	      catch (NumberFormatException NFE) {		  throw new SQLException("Illegal parameter '" + 					 Info.getProperty("initialTimeout") 					 +"' for initialTimeout", "0S100");	      }	  }      }            if (Info.getProperty("maxRows") != null) {	  try {	      int n = Integer.parseInt(Info.getProperty("maxRows"));	      	      if (n == 0) {		  n = -1;	      } // adjust so that it will become MysqlDefs.MAX_ROWS              // in execSQL()	      _max_rows = n;	  }	  catch (NumberFormatException NFE) {	      throw new SQLException("Illegal parameter '" + 				     Info.getProperty("maxRows") 				     +"' for maxRows", "0S100");	  }      }            if (Info.getProperty("useUnicode") != null) {	  String UseUnicode = Info.getProperty("useUnicode").toUpperCase();	  if (UseUnicode.startsWith("TRUE")) {	      _do_unicode = true;	  }	  if (Info.getProperty("characterEncoding") != null) {	      _Encoding = Info.getProperty("characterEncoding");	      	      // Attempt to use the encoding, and bail out if it	      // can't be used	      try {		  String TestString = "abc";		  TestString.getBytes(_Encoding);	      }	      catch (UnsupportedEncodingException UE) {		  throw new SQLException("Unsupported character encoding '" + 					 _Encoding + "'.", "0S100"); 	      }	  }      }            if (Driver.debug)	  System.out.println("Connect: " + _User + " to " + _Database);      try {	  _IO = new MysqlIO(Host, port);	  _IO.init(_User, _Password);	  _IO.sendCommand(MysqlDefs.INIT_DB, _Database, null);	  _isClosed = false;      }       catch (java.sql.SQLException E) {	  throw E;      }      catch (Exception E) {	  E.printStackTrace();	  throw new java.sql.SQLException("Cannot connect to MySQL server on " + _Host + ":" + _port + ". Is there a MySQL server running on the machine/port you are trying to connect to? (" + E.getClass().getName() + ")", "08S01");      }  }    /**   * SQL statements without parameters are normally executed using   * Statement objects.  If the same SQL statement is executed many   * times, it is more efficient to use a PreparedStatement   *   * @return a new Statement object   * @exception java.sql.SQLException passed through from the constructor   */    public java.sql.Statement createStatement() throws java.sql.SQLException    {	if (Driver.trace) {	    Object[] Args = new Object[0];	    Debug.methodCall(this, "createStatement", Args);	}      if (Driver.debug) {       System.out.println(this + " creating statement.");      }              org.gjt.mm.mysql.Statement Stmt = new org.gjt.mm.mysql.Statement(this, _Database);	if (_max_rows != -1) {	    Stmt.setMaxRows(_max_rows);	}	if (Driver.trace) {	    Debug.returnValue(this, "createStatement", Stmt);	}              return Stmt;    }  /**   * A SQL statement with or without IN parameters can be pre-compiled   * and stored in a PreparedStatement object.  This object can then   * be used to efficiently execute this statement multiple times.   *    * <p>   * <B>Note:</B> This method is optimized for handling parametric   * SQL statements that benefit from precompilation if the driver   * supports precompilation.    * In this case, the statement is not sent to the database until the   * PreparedStatement is executed.  This has no direct effect on users;   * however it does affect which method throws certain java.sql.SQLExceptions   *   * <p>   * MySQL does not support precompilation of statements, so they   * are handled by the driver.    *   * @param sql a SQL statement that may contain one or more '?' IN   *    parameter placeholders   * @return a new PreparedStatement object containing the pre-compiled   *    statement.   * @exception java.sql.SQLException if a database access error occurs.   */  public java.sql.PreparedStatement prepareStatement(String Sql) throws java.sql.SQLException  {      if (Driver.trace) {	  Object[] Args = {Sql};	  Debug.methodCall(this, "prepareStatement", Args);      }      PreparedStatement PStmt = new org.gjt.mm.mysql.PreparedStatement(this, Sql, _Database);      if (Driver.trace) {	  Debug.returnValue(this, "prepareStatement", PStmt);      }    return PStmt;  }  /**   * A SQL stored procedure call statement is handled by creating a   * CallableStatement for it.  The CallableStatement provides methods   * for setting up its IN and OUT parameters and methods for executing   * it.   *   * <B>Note:</B> This method is optimised for handling stored procedure   * call statements.  Some drivers may send the call statement to the   * database when the prepareCall is done; others may wait until the   * CallableStatement is executed.  This has no direct effect on users;   * however, it does affect which method throws certain java.sql.SQLExceptions   *   * @param sql a SQL statement that may contain one or more '?' parameter   *    placeholders.  Typically this statement is a JDBC function call   *    escape string.   * @return a new CallableStatement object containing the pre-compiled   *    SQL statement   * @exception java.sql.SQLException if a database access error occurs   */  public java.sql.CallableStatement prepareCall(String Sql) throws java.sql.SQLException  {      if (Driver.trace) {	  Object[] Args = {Sql};	  Debug.methodCall(this, "prepareCall", Args);      }    throw new java.sql.SQLException("Callable statments not suppoted.", "S1C00");   }  /**   * A driver may convert the JDBC sql grammar into its system's   * native SQL grammar prior to sending it; nativeSQL returns the   * native form of the statement that the driver would have sent.   *   * @param sql a SQL statement that may contain one or more '?'   *    parameter placeholders   * @return the native form of this statement   * @exception java.sql.SQLException if a database access error occurs   */  public String nativeSQL(String Sql) throws java.sql.SQLException  {      if (Driver.trace) {	  Object[] Args = {Sql};	  Debug.methodCall(this, "nativeSQL", Args);	  Debug.returnValue(this, "nativeSQL", Sql);      }    return Sql;  }  /**   * If a connection is in auto-commit mode, than all its SQL   * statements will be executed and committed as individual   * transactions.  Otherwise, its SQL statements are grouped   * into transactions that are terminated by either commit()   * or rollback().  By default, new connections are in auto-   * commit mode.  The commit occurs when the statement completes   * or the next execute occurs, whichever comes first.  In the   * case of statements returning a ResultSet, the statement   * completes when the last row of the ResultSet has been retrieved   * or the ResultSet has been closed.  In advanced cases, a single   * statement may return multiple results as well as output parameter   * values.  Here the commit occurs when all results and output param   * values have been retrieved.   *   * <p><b>Note:</b> MySQL does not support transactions, so this   *                 method is a no-op.   *   * @param autoCommit - true enables auto-commit; false disables it   * @exception java.sql.SQLException if a database access error occurs   */  public void setAutoCommit(boolean autoCommit) throws java.sql.SQLException  {      if (Driver.trace) {	  Object[] Args = {new Boolean(autoCommit)};	  Debug.methodCall(this, "setAutoCommit", Args);      }      if (autoCommit == false) {	  throw new SQLException("Cannot disable AUTO_COMMIT", "08003");      }      return;  }  /**   * gets the current auto-commit state   *   * @return Current state of the auto-commit mode   * @exception java.sql.SQLException (why?)   * @see setAutoCommit   */  public boolean getAutoCommit() throws java.sql.SQLException  {      if (Driver.trace) {	  Object[] Args = new Object[0];	  Debug.methodCall(this, "getAutoCommit", Args);	  Debug.returnValue(this, "getAutoCommit", new Boolean(_autoCommit));      }    return _autoCommit;  }  /**   * The method commit() makes all changes made since the previous   * commit/rollback permanent and releases any database locks currently   * held by the Connection.  This method should only be used when   * auto-commit has been disabled.  (If autoCommit == true, then we   * just return anyhow)   *    * <p><b>Note:</b> MySQL does not support transactions, so this   *                 method is a no-op.   *   * @exception java.sql.SQLException if a database access error occurs   * @see setAutoCommit   */

⌨️ 快捷键说明

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