分页查询<br>
此方法不会关闭Connection

@param <T> 结果对象类型
@param conn 数据库连接对象
@param fields 返回的字段列表，null则返回所有字段
@param where 条件实体类（包含表名）
@param page 分页对象
@param rsh 结果集处理对象
@return 结果对象
@throws SQLException SQL执行异常
162299
public <T> T page(Connection conn, Collection<String> fields, Entity where, Page page, RsHandler<T> rsh) throws SQLException {
		checkConn(conn);
		if(null == page){
			return this.find(conn, fields, where, rsh);
		}
		
		final Query query = new Query(SqlUtil.buildConditions(where), where.getTableName());
		query.setFields(fields);
		query.setPage(page);
		return SqlExecutor.queryAndClosePs(dialect.psForPage(conn, query), rsh);
	}
623367
private Object executeExp(PageContext pc, SQL sql, Query qr, Expression exp, int row) throws PageException {
	// print.e("name:"+exp.getClass().getName());
	if (exp instanceof Value) return ((Value) exp).getValue();// executeConstant(sql,qr, (Value)exp, row);
	if (exp instanceof Column) return executeColumn(sql, qr, (Column) exp, row);
	if (exp instanceof Operation) return executeOperation(pc, sql, qr, (Operation) exp, row);
	if (exp instanceof BracketExpression) return executeBracked(pc, sql, qr, (BracketExpression) exp, row);
	throw new DatabaseException("unsupported sql statement [" + exp + "]", null, sql, null);
    }
605564
function ResultSet(conn, query, values, options, rs) {
  this.query = query;
  this.metadata = rs.metadata;
  this.rows = rs.rows;
  this._conn = conn;
  this._values = values;
  this._options = options;
}
235034
public Query execute(PageContext pc, SQL sql, int maxrows, int fetchsize, TimeSpan timeout) throws PageException {
	Stopwatch stopwatch = new Stopwatch(Stopwatch.UNIT_NANO);
	stopwatch.start();
	String prettySQL = null;
	Selects selects = null;

	// First Chance
	try {
	    SelectParser parser = new SelectParser();
	    selects = parser.parse(sql.getSQLString());

	    Query q = qoq.execute(pc, sql, selects, maxrows);
	    q.setExecutionTime(stopwatch.time());

	    return q;
	}
	catch (SQLParserException spe) {
	    // lucee.print.printST(spe);
	    // sp
	    // lucee.print.out("sql parser crash at:");
	    // lucee.print.out("--------------------------------");
	    // lucee.print.out(sql.getSQLString().trim());
	    // lucee.print.out("--------------------------------");
	    // print.e("1:"+sql.getSQLString());
	    prettySQL = SQLPrettyfier.prettyfie(sql.getSQLString());
	    // print.e("2:"+prettySQL);
	    try {
		Query query = executer.execute(pc, sql, prettySQL, maxrows);
		query.setExecutionTime(stopwatch.time());
		return query;
	    }
	    catch (PageException ex) {
		// lucee.print.printST(ex);
		// lucee.print.out("old executor/zql crash at:");
		// lucee.print.out("--------------------------------");
		// lucee.print.out(sql.getSQLString().trim());
		// lucee.print.out("--------------------------------");

	    }

	}
	catch (PageException e) {
	    // throw e;
	    // print.out("new executor crash at:");
	    // print.out("--------------------------------");
	    // print.out(sql.getSQLString().trim());
	    // print.out("--------------------------------");
	}
	// if(true) throw new RuntimeException();

	// SECOND Chance with hsqldb
	try {
	    boolean isUnion = false;
	    Set<String> tables = null;
	    if (selects != null) {
		HSQLUtil2 hsql2 = new HSQLUtil2(selects);
		isUnion = hsql2.isUnion();
		tables = hsql2.getInvokedTables();
	    }
	    else {
		if (prettySQL == null) prettySQL = SQLPrettyfier.prettyfie(sql.getSQLString());
		HSQLUtil hsql = new HSQLUtil(prettySQL);
		tables = hsql.getInvokedTables();
		isUnion = hsql.isUnion();
	    }

	    String strSQL = StringUtil.replace(sql.getSQLString(), "[", "", false);
	    strSQL = StringUtil.replace(strSQL, "]", "", false);
	    sql.setSQLString(strSQL);
	    return _execute(pc, sql, maxrows, fetchsize, timeout, stopwatch, tables, isUnion);

	}
	catch (ParseException e) {
	    throw new DatabaseException(e.getMessage(), null, sql, null);
	}

    }
775936
public Page<T> page(String sql, Object[] params, PageRow pageRow) {
        this.beforeCheck();
        Connection conn = getConn();
        try {
            String countSql = useSQL ? "SELECT COUNT(*) FROM (" + sql + ") tmp" : buildCountSQL(sql);

            long count = conn.createQuery(countSql)
                    .withParams(params)
                    .executeAndFetchFirst(Long.class);

            Page<T> pageBean = new Page<>(count, pageRow.getPageNum(), pageRow.getPageSize());

            ifThen(count > 0, () -> {
                String pageSQL = this.buildPageSQL(sql, pageRow);
                List<T> list = conn.createQuery(pageSQL)
                        .withParams(params)
                        .setAutoDeriveColumnNames(true)
                        .throwOnMappingFailure(false)
                        .executeAndFetch(modelClass);

                this.setJoin(list);
                pageBean.setRows(list);
            });

            return pageBean;
        } finally {
            this.closeConn(conn);
            this.clean(null);
        }
    }
909329
public PageResult<Entity> page(Connection conn, Collection<String> fields, Entity where, int page, int numPerPage) throws SQLException {
		checkConn(conn);
		
		final int count = count(conn, where);
		PageResultHandler pageResultHandler = PageResultHandler.create(new PageResult<Entity>(page, numPerPage, count));
		return this.page(conn, fields, where, page, numPerPage, pageResultHandler);
	}
90280
boolean connect() throws SQLException {
    try {
      if (driver != null && driver.length() != 0) {
        Class.forName(driver);
      }
    } catch (ClassNotFoundException cnfe) {
      return sqlLine.error(cnfe);
    }

    boolean foundDriver = false;
    Driver theDriver = null;
    try {
      theDriver = DriverManager.getDriver(url);
      foundDriver = theDriver != null;
    } catch (Exception e) {
      // ignore
    }

    if (!foundDriver) {
      sqlLine.output(sqlLine.loc("autoloading-known-drivers", url));
      sqlLine.registerKnownDrivers();
      theDriver = DriverManager.getDriver(url);
    }

    try {
      close();
    } catch (Exception e) {
      return sqlLine.error(e);
    }

    // Avoid using DriverManager.getConnection(). It is a synchronized
    // method and thus holds the lock while making the connection.
    // Deadlock can occur if the driver's connection processing uses any
    // synchronized DriverManager methods.  One such example is the
    // RMI-JDBC driver, whose RJDriverServer.connect() method uses
    // DriverManager.getDriver(). Because RJDriverServer.connect runs in
    // a different thread (RMI) than the getConnection() caller (here),
    // this sequence will hang every time.
/*
          connection = DriverManager.getConnection (url, username, password);
*/
    // Instead, we use the driver instance to make the connection

    connection = theDriver.connect(url, info);
    meta = (DatabaseMetaData) Proxy.newProxyInstance(
        DatabaseMetaData.class.getClassLoader(),
        new Class[] {DatabaseMetaData.class},
        new DatabaseMetaDataHandler(connection.getMetaData()));
    try {
      sqlLine.debug(
          sqlLine.loc("connected",
              meta.getDatabaseProductName(),
              meta.getDatabaseProductVersion()));
    } catch (Exception e) {
      sqlLine.handleException(e);
    }

    try {
      sqlLine.debug(
          sqlLine.loc("driver",
              meta.getDriverName(),
              meta.getDriverVersion()));
    } catch (Exception e) {
      sqlLine.handleException(e);
    }

    try {
      connection.setAutoCommit(sqlLine.getOpts().getAutoCommit());
      sqlLine.autocommitStatus(connection);
    } catch (Exception e) {
      sqlLine.handleException(e);
    }

    try {
      // nothing is done off of this command beyond the handle so no
      // need to use the callback.
      sqlLine.getCommands().isolation("isolation: " + sqlLine.getOpts()
          .getIsolation(),
          new DispatchCallback());
      initSyntaxRule();
    } catch (Exception e) {
      sqlLine.handleException(e);
    }

    sqlLine.showWarnings();

    return true;
  }
322769
@When("^I query the database with '(.+?)'$")
    public void selectData(String query) throws Exception {
        Statement myStatement = null;
        //postgres table
        List<String> sqlTable = new ArrayList<String>();
        List<String> sqlTableAux = new ArrayList<String>();
        Connection myConnection = this.commonspec.getConnection();
        java.sql.ResultSet rs = null;
        try {
            myStatement = myConnection.createStatement();
            rs = myStatement.executeQuery(query);
            //column names
            ResultSetMetaData resultSetMetaData = rs.getMetaData();
            int count = resultSetMetaData.getColumnCount();
            for (int i = 1; i <= count; i++) {
                sqlTable.add(resultSetMetaData.getColumnName(i).toString());
            }
            //takes column names and column count
            while (rs.next()) {
                for (int i = 1; i <= count; i++) {
                    //aux list without column names
                    sqlTableAux.add(rs.getObject(i).toString());
                }
            }
            sqlTable.addAll(sqlTableAux);

            //sends raws to environment variable
            for (int i = 0; i < sqlTable.size(); i++) {
                ThreadProperty.set("queryresponse" + i, sqlTable.get(i));
            }
            ThreadProperty.remove("queryresponse" + sqlTable.size());
            rs.close();
            myStatement.close();
        } catch (Exception e) {
            e.printStackTrace();
            Assertions.assertThat(rs).as("There are no response from SELECT").isNotNull();
        }
    }
1265079
public User get( Connection conn, int id) throws SQLException {
        ResultSetHandler<User> h = new BeanHandler<User>(User.class);
        String sql =
            "SELECT id,username,fullname,type,emailaddress,registered_ts,invited_by,enabled \n"+
            "FROM userbase \n"+
            "WHERE id=?";
        return run.query(conn, sql, h, id);
    }
680645
public static CallableStatement prepareCall(Connection conn, String sql, Object... params) throws SQLException {
		Assert.notBlank(sql, "Sql String must be not blank!");

		sql = sql.trim();
		SqlLog.INSTASNCE.log(sql, params);
		final CallableStatement call = conn.prepareCall(sql);
		fillParams(call, params);
		return call;
	}
94858
public int count(Connection conn, Entity where) throws SQLException {
		checkConn(conn);
		
		final Query query = new Query(SqlUtil.buildConditions(where), where.getTableName());
		PreparedStatement ps = null;
		try {
			ps = dialect.psForCount(conn, query);
			return SqlExecutor.query(ps, new NumberHandler()).intValue();
		} catch (SQLException e) {
			throw e;
		} finally {
			DbUtil.close(ps);
		}
	}
880235
public <T> T find(Query query, RsHandler<T> rsh) throws SQLException {
		Connection conn = null;
		try {
			conn = this.getConnection();
			return runner.find(conn, query, rsh);
		} catch (SQLException e) {
			throw e;
		} finally {
			this.closeConnection(conn);
		}
	}
221094
public static void returnConnection(Connection conn) throws SQLException {
        if (conn == null) {
            return;
        }
        String dsName = openConnDsName.get().get(conn);
        OpenConnStats connStats = dsName != null ? openConnStats.get().get(dsName) : null;
        if (connStats == null) {
            conn.close();
        } else {
            long value = connStats.counter.decrementAndGet();
            if (value <= 0) {
                try {
                    try {
                        if (connStats.inTransaction) {
                            conn.commit();
                        }
                    } catch (Exception e) {
                        conn.rollback();
                    } finally {
                        try {
                            conn.setAutoCommit(true);
                        } finally {
                            connStats.inTransaction = false;
                            conn.close();
                        }
                    }
                } finally {
                    openConnStats.get().remove(dsName);
                    openConnDsName.get().remove(conn);
                }
            }
        }
    }
812956
async function runQuery(query, connection) {
  // Connection here doesn't actually matter.
  // Someday this mock could get fancy and change output based on some connection value
  // For now validate that it is getting passed
  const { maxRows } = connection;

  // To determine the content of this mock query, inspect values from comments
  // Example format
  // -- dimensions = department 10, color 10, product 10, orderdate|orderdatetime 500
  // -- measures = cost, revenue, profit, <anythingyouwant>
  // -- orderby = department asc, product desc
  // -- limit = 100
  const dimensions = [];
  const measures = [];
  const orderByFields = [];
  const orderByDirections = [];
  let limit;

  query
    .split('\n')
    .map(line => line.trim())
    .filter(line => line.startsWith('--'))
    .map(line => line.replace('--', ''))
    .forEach(line => {
      const [fieldType, fieldData] = line
        .split('=')
        .map(p => p.trim().toLowerCase());

      if (!fieldData) {
        return;
      }

      // fieldData is something like <fieldname> <direction>, <field2> <direction>
      // or 100
      fieldData
        .split(',')
        .map(p => p.trim())
        .forEach(part => {
          if (fieldType === 'limit') {
            limit = parseInt(part);
          } else if (fieldType === 'dimensions') {
            const [fieldName, numString] = part.split(' ').map(p => p.trim());
            if (!fieldValues[fieldName]) {
              throw new Error(
                `Unknown ${fieldName}. must be one of: ${Object.keys(
                  fieldValues
                ).join(', ')}`
              );
            }
            dimensions.push({
              name: fieldName,
              values: fieldValues[fieldName].slice(0, parseInt(numString))
            });
          } else if (fieldType === 'measures') {
            measures.push(part);
          } else if (fieldType === 'orderby') {
            const [fieldName, direction] = part.split(' ').map(p => p.trim());
            if (!direction) {
              throw new Error('direction required. Must be asc or desc');
            }
            orderByFields.push(fieldName);
            orderByDirections.push(direction);
          } else {
            throw new Error(
              `Unknown ${fieldType}. Must be dimensions, measures, orderby, or limit`
            );
          }
        });
    });

  if (!dimensions.length) {
    throw new Error('dimensions required');
  }

  // Assemble dimensions and things
  let rows = [];
  dimensions.forEach(dimension => {
    rows = cartesianify(rows, dimension);
  });

  if (measures.length) {
    rows.forEach(row => {
      measures.forEach(measure => {
        const date = row.orderdate || row.orderdatetime;
        if (date) {
          const doy = moment.utc(date).dayOfYear();
          row[measure] = 10 + Math.round(doy * Math.random());
        } else {
          row[measure] = Math.round(Math.random() * 1000);
        }
      });
    });
  }

  if (orderByFields.length) {
    rows = _.orderBy(rows, orderByFields, orderByDirections);
  }

  if (limit) {
    rows = rows.slice(0, limit);
  }

  return { rows: rows.slice(0, maxRows), incomplete: rows.length > maxRows };
}
1304347
public int insert(Connection conn, Entity record) throws SQLException {
		checkConn(conn);
		if(CollectionUtil.isEmpty(record)){
			throw new SQLException("Empty entity provided!");
		}
		PreparedStatement ps = null;
		try {
			ps = dialect.psForInsert(conn, record);
			return ps.executeUpdate();
		} catch (SQLException e) {
			throw e;
		} finally {
			DbUtil.close(ps);
		}
	}
228972
public Connection connect(final String url, final Properties props) throws SQLException {

    UrlParser urlParser = UrlParser.parse(url, props);
    if (urlParser == null || urlParser.getHostAddresses() == null) {
      return null;
    } else {
      return MariaDbConnection.newConnection(urlParser, null);
    }

  }
401230
private static void addTable(Connection conn, PageContext pc, String name, Query query, boolean doSimpleTypes, ArrayList<String> usedTables)
	    throws SQLException, PageException {
	Statement stat;
	usedTables.add(name);
	stat = conn.createStatement();
	Key[] keys = CollectionUtil.keys(query);
	int[] types = query.getTypes();
	int[] innerTypes = toInnerTypes(types);
	// CREATE STATEMENT
	String comma = "";
	StringBuilder create = new StringBuilder("CREATE TABLE " + name + " (");
	StringBuilder insert = new StringBuilder("INSERT INTO  " + name + " (");
	StringBuilder values = new StringBuilder("VALUES (");
	for (int i = 0; i < keys.length; i++) {
	    String key = keys[i].getString();
	    String type = (doSimpleTypes) ? "VARCHAR_IGNORECASE" : toUsableType(types[i]);

	    create.append(comma + key);
	    create.append(" ");
	    create.append(type);
	    insert.append(comma + key);
	    values.append(comma + "?");
	    comma = ",";
	}
	create.append(")");
	insert.append(")");
	values.append(")");
	stat.execute(create.toString());
	PreparedStatement prepStat = conn.prepareStatement(insert.toString() + values.toString());

	// INSERT STATEMENT
	// HashMap integerTypes=getIntegerTypes(types);

	int count = query.getRecordcount();
	QueryColumn[] columns = new QueryColumn[keys.length];
	for (int i = 0; i < keys.length; i++) {
	    columns[i] = query.getColumn(keys[i]);
	}
	for (int y = 0; y < count; y++) {
	    for (int i = 0; i < keys.length; i++) {
		int type = innerTypes[i];
		Object value = columns[i].get(y + 1, null);

		// print.out("*** "+type+":"+Caster.toString(value));
		if (doSimpleTypes) {

		    prepStat.setObject(i + 1, Caster.toString(value));
		}
		else {
		    if (value == null) prepStat.setNull(i + 1, types[i]);
		    else if (type == BINARY) prepStat.setBytes(i + 1, Caster.toBinary(value));
		    else if (type == DATE) {
			// print.out(new java.util.Date(new
			// Date(DateCaster.toDateAdvanced(value,pc.getTimeZone()).getTime()).getTime()));

			prepStat.setTimestamp(i + 1, (value.equals("")) ? null : new Timestamp(DateCaster.toDateAdvanced(query.getAt(keys[i], y + 1), pc.getTimeZone()).getTime()));
			// prepStat.setObject(i+1,Caster.toDate(value,null));
			// prepStat.setDate(i+1,(value==null || value.equals(""))?null:new
			// Date(DateCaster.toDateAdvanced(value,pc.getTimeZone()).getTime()));
		    }
		    else if (type == TIME)
			prepStat.setTime(i + 1, (value.equals("")) ? null : new Time(DateCaster.toDateAdvanced(query.getAt(keys[i], y + 1), pc.getTimeZone()).getTime()));
		    else if (type == TIMESTAMP)
			prepStat.setTimestamp(i + 1, (value.equals("")) ? null : new Timestamp(DateCaster.toDateAdvanced(query.getAt(keys[i], y + 1), pc.getTimeZone()).getTime()));
		    else if (type == DOUBLE) prepStat.setDouble(i + 1, (value.equals("")) ? 0 : Caster.toDoubleValue(query.getAt(keys[i], y + 1)));
		    else if (type == INT) prepStat.setLong(i + 1, (value.equals("")) ? 0 : Caster.toLongValue(query.getAt(keys[i], y + 1)));
		    else if (type == STRING) prepStat.setObject(i + 1, Caster.toString(value));
		}

	    }
	    prepStat.execute();
	}

    }