mysqli.java

来自「RESIN 3.2 最新源码」· Java 代码 · 共 1,588 行 · 第 1/3 页

JAVA
1,588
字号
    int matched = affected_rows();    int changed = matched;    int duplicates = 0;    int warnings = 0;    SQLWarning warning = getWarnings();    while (warning != null) {      warning = warning.getNextWarning();      warnings++;    }    if (_lastSql == LastSqlType.UPDATE)      buff.append("Rows matched: ");    else      buff.append("Records: ");    buff.append(matched);    if (_lastSql == LastSqlType.UPDATE) {      buff.append("  Changed: "); // PHP adds 2 spaces before Changed:      buff.append(changed);    } else {      buff.append(" Duplicates: ");      buff.append(duplicates);    }    if (_lastSql == LastSqlType.UPDATE)      buff.append("  Warnings: "); // Only update has 2 spaces here    else      buff.append(" Warnings: ");    buff.append(warnings);    return env.createString(buff.toString());  }  /**   * Returns the port number.   */  public int get_port_number()  {    return getPort();  }  /**   * Quercus function to get the field 'protocol_version'.   */  public int getprotocol_version()  {    return get_proto_info();  }    /**   * Returns the protocol information.   */  public int get_proto_info()  {    return 10;  }  /**   * Quercus function to get the field 'server_info'.   */  public StringValue getserver_info(Env env)  {    return get_server_info(env);  }    /**   * Returns the server information.   */  public StringValue get_server_info(Env env)  {    try {      return env.createString(validateConnection().getServerInfo());    } catch (SQLException e) {      return env.getEmptyString();    }  }  /**   * Quercus function to get the field 'server_version'.   */  public int getserver_version()  {    return get_server_version();  }  /**   * Returns the server information.   */  public int get_server_version()  {    try {      String info = validateConnection().getServerInfo();      return infoToVersion(info);    } catch (SQLException e) {      return 0;    }  }  /**   * Quercus function to get the field 'field_count'.   */  public int getfield_count()  {    return field_count();  }    /**   * Returns the number of columns in the last query.   */  public int field_count()  {    return validateConnection().getFieldCount();  }  /**   * Quercus function to get the field 'insert_id'.   */  public Value getinsert_id(Env env)  {    return insert_id(env);  }    /**   * returns ID generated for an AUTO_INCREMENT column by the previous   * INSERT query on success, 0 if the previous query does not generate   * an AUTO_INCREMENT value, or FALSE if no MySQL connection was established   *   */  public Value insert_id(Env env)  {    try {      JdbcConnectionResource connV = validateConnection();      Connection conn = connV.getConnection(env);      if (conn == null)        return BooleanValue.FALSE;            Statement stmt = null;      try {        stmt = conn.createStatement();        ResultSet rs = stmt.executeQuery("SELECT @@identity");        if (rs.next())          return LongValue.create(rs.getLong(1));        else          return BooleanValue.FALSE;      } finally {        if (stmt != null)          stmt.close();      }    } catch (SQLException e) {      log.log(Level.FINE, e.toString(), e);      return BooleanValue.FALSE;    }  }  @ReturnNullAsFalse  public JdbcResultResource list_dbs()  {    return validateConnection().getCatalogs();  }  /**   * Check for more results in a multi-query   */  public boolean more_results()  {    return ((Mysqli) validateConnection()).moreResults();  }  /**   * executes one or multiple queries which are   * concatenated by a semicolon.   */  public boolean multi_query(Env env, StringValue query)  {    return ((Mysqli) validateConnection()).multiQuery(env, query);  }  /**   * prepares next result set from a previous call to   * mysqli_multi_query   */  public boolean next_result()  {    return ((Mysqli) validateConnection()).nextResult();  }  /**   * Sets a mysqli option.   */  public boolean options(int option, Value value)  {    return false;  }  /**   * Executes a query.   *   * @param env the PHP executing environment   * @param sql the escaped query string (can contain escape sequences like `\n' and `\Z')   * @param resultMode ignored   *   * @return a {@link JdbcResultResource}, or null for failure   */  public Value query(Env env,                     StringValue sqlV,                     @Optional("MYSQLI_STORE_RESULT") int resultMode)  {    String sql = sqlToString(env, sqlV);        return realQuery(env, sql);  }    private static String sqlToString(Env env, StringValue sql)  {    byte []bytes = sql.toBytes();        try {      return new String(bytes, ENCODING);    } catch (UnsupportedEncodingException e) {      throw new QuercusException(e);    }  }  /**   * Intercept Mysql specific query before sending to JDBC driver   * to handle any special cases.   */  @Override  protected Value realQuery(Env env, String sql)  {    clearErrors();        _lastSql = null;    setResultResource(null);    try {      // Check for valid conneciton      Connection conn = getConnection(env);            if (conn == null)        return BooleanValue.FALSE;      SqlParseToken tok = parseSqlToken(sql, null);      if (tok != null	  && tok.matchesFirstChar('U', 'u')	  && tok.matchesToken("USE")) {        // Mysql "USE DBNAME" statement.        //        // The Mysql JDBC driver does not properly implement getCatalog()        // when calls to setCatalog() are mixed with SQL USE statements.        // Work around this problem by translating a SQL USE statement        // into a JDBC setCatalog() invocation. The setCatalog() API in        // the ConnectorJ implementation just creates a USE statement        // anyway. This also makes sure the database pool logic knows        // which database is currently selected. If a second call to        // select the current database is found, it is a no-op.        tok = parseSqlToken(sql, tok);        if (tok != null) {          String dbname = tok.toUnquotedString();          setCatalog(dbname);          return BooleanValue.TRUE;        }      }      else if (tok != null	       && tok.matchesFirstChar('U', 'u')	       && tok.matchesToken("UPDATE")) {        // SQL UPDATE statement        _lastSql = LastSqlType.UPDATE;      }      else if (tok != null	       && tok.matchesFirstChar('D', 'd')	       && tok.matchesToken("DESCRIBE")) {        // SQL DESCRIBE statement        _lastSql = LastSqlType.DESCRIBE;      }      return super.realQuery(env, sql);    } catch (SQLException e) {      saveErrors(e);      log.log(Level.FINEST, e.toString(), e);      return BooleanValue.FALSE;    } catch (IllegalStateException e) {      log.log(Level.FINEST, e.toString(), e);            // #2184, some drivers return this on closed connection      saveErrors(new SQLExceptionWrapper(e));      return BooleanValue.FALSE;    }  }  /**   * Execute an single query against the database whose result can then be retrieved   * or stored using the mysqli_store_result() or mysqli_use_result() functions.   *   * @param env the PHP executing environment   * @param query the escaped query string (can contain escape sequences like `\n' and `\Z')   */  public boolean real_query(Env env,                            StringValue query)  {    // Assume that the query argument contains just one query. Reuse the    // result management logic in multiQuery(), so that a future call to    // mysqli_store_result() will work as expected.    return multiQuery(env, query);  }  /**   * returns a prepared statement or null on error.   */  public MysqliStatement prepare(Env env, StringValue query)  {    MysqliStatement stmt = new MysqliStatement((Mysqli) validateConnection());    boolean result = stmt.prepare(env, query);    if (! result) {      stmt.close();      return null;    }    return stmt;  }  /**   * Connects to the underlying database.   */  public boolean real_connect(Env env,                              @Optional("localhost") StringValue host,                              @Optional StringValue userName,                              @Optional StringValue password,                              @Optional StringValue dbname,                              @Optional("3306") int port,                              @Optional StringValue socket,                              @Optional int flags)  {    return connectInternal(env,                           host.toString(),                           userName.toString(),                           password.toString(),                           dbname.toString(),                           port,                           socket.toString(),                           flags,                           null,                           null);  }  /**   * Escapes the string   */  public StringValue real_escape_string(StringValue str)  {    return realEscapeString(str);  }  /**   * Rolls the current transaction back.   */  public boolean rollback()  {    return super.rollback();  }  /**   * Selects the underlying database/catalog to use.   *   * @param dbname the name of the database to select.   */  public boolean select_db(StringValue dbname)  {    try {      if (isConnected()) {        String catalog = dbname.toString();        getEnv().getQuercus().setSpecial("mysql.catalog", catalog);	        validateConnection().setCatalog(catalog);                return true;      }      else        return false;    } catch (SQLException e) {      log.log(Level.FINE, e.toString(), e);      getEnv().warning(e.getMessage());      return false;    }  }  /**   * Sets the character set   */  public boolean set_charset(String charset)  {    return false;  }  /**   * Sets a mysqli option   */  public boolean set_opt(int option, Value value)  {    return options(option, value);  }  /**   * Quercus function to get the field 'sqlstate'.   */  public StringValue getsqlstate(Env env)  {    return sqlstate(env);  }  /**   * Returns the SQLSTATE error   */  public StringValue sqlstate(Env env)  {    int code = validateConnection().getErrorCode();    return env.createString(lookupSqlstate(code));  }  /**   * Given an error number, returns a SQLSTATE error string.   */  static String lookupSqlstate(int errno)  {    if (errno == 0)      return "00000";    else      return "HY" + errno;  }  /**   * returns a string with the status of the connection   * or FALSE if error   */  public Value stat(Env env)  {    try {      JdbcConnectionResource connV = validateConnection();      Connection conn = connV.getConnection(env);            if (conn == null)        return BooleanValue.FALSE;            Statement stmt = null;      StringBuilder str = new StringBuilder();      try {        stmt = conn.createStatement();        stmt.execute("SHOW STATUS");        ResultSet rs = stmt.getResultSet();        while (rs.next()) {          if (str.length() > 0)            str.append(' ');          str.append(rs.getString(1));          str.append(": ");          str.append(rs.getString(2));        }        return env.createString(str.toString());      } finally {        if (stmt != null)          stmt.close();      }    } catch (SQLException e) {      log.log(Level.FINE, e.toString(), e);      return BooleanValue.FALSE;    }  }  /**   * returns a string with the status of the connection   *  public Value stat()  {    clearErrors();    StringBuilder str = new StringBuilder();    try {      Statement stmt = _conn.createStatement();      stmt.execute("SHOW STATUS");      ResultSet rs = stmt.getResultSet();      while (rs.next()) {        if (str.length() > 0)          str.append(' ');        str.append(rs.getString(1));        str.append(": ");        str.append(rs.getString(2));      }      return new StringValueImpl(str.toString());    } catch (SQLException e) {      saveErrors(e);      log.log(Level.WARNING, e.toString(), e);      return BooleanValue.FALSE;    }  }  */  /**   * returns a statement for use with

⌨️ 快捷键说明

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