Convenience method to retrieve an entire result
set into memory.

@param sql the SQL statement to be executed
@param args arguments for the SQL statement, '%q' substitution
@param tbl TableResult to receive result set
355793
public void get_table( String sql, String args[], TableResult tbl ) throws jsqlite.Exception {
        tbl.clear();
        if (!is3()) {
            try {
                exec(sql, tbl, args);
            } catch (jsqlite.Exception e) {
                if (tbl.maxrows <= 0 || !tbl.atmaxrows) {
                    throw e;
                }
            }
        } else {
            synchronized (this) {
                /* only one statement !!! */
                Vm vm = compile(sql, args);
                if (tbl.maxrows > 0) {
                    while( tbl.nrows < tbl.maxrows && vm.step(tbl) ) {
                        set_last_error(vm.error_code);
                    }
                } else {
                    while( vm.step(tbl) ) {
                        set_last_error(vm.error_code);
                    }
                }
                vm.finalize();
            }
        }
    }
1036305
public Object querySingleResult(String sql, String[] args, int column,
			GeoPackageDataType dataType) {
		return db.querySingleResult(sql, args, column, dataType);
	}
978619
public static String execSqlQueryTabular(@NotNull final SQLInputs sqlInputs) throws Exception {
        ConnectionService connectionService = new ConnectionService();
        try (final Connection connection = connectionService.setUpConnection(sqlInputs)){
            connection.setReadOnly(true);

            final Statement statement = connection.createStatement(sqlInputs.getResultSetType(), sqlInputs.getResultSetConcurrency());
            statement.setQueryTimeout(sqlInputs.getTimeout());

            final ResultSet resultSet = statement.executeQuery(sqlInputs.getSqlCommand());

            final String resultSetToTable = Format.resultSetToTable(resultSet, sqlInputs.isNetcool());
            resultSet.close();
            return resultSetToTable;
        }
    }
1154283
public TableResult get_table( String sql, String args[] ) throws jsqlite.Exception {
        return get_table(sql, 0, args);
    }
223869
@Override
    public ResultSet executeQuery(String sql) throws SQLException
    {
        checkClosed();
        VoltSQL query = VoltSQL.parseSQL(sql);
        if (!query.isOfType(VoltSQL.TYPE_SELECT)) {
            throw SQLError.get(SQLError.ILLEGAL_STATEMENT, sql);
        }
        return this.executeQuery(query);
    }
1112673
@Override
	public int[] doBatch(final SqlContext sqlContext, final PreparedStatement preparedStatement, final int[] result) {
		if (LOG.isDebugEnabled()) {
			int[] counts = result;
			try {
				counts = new int[] { preparedStatement.getUpdateCount() };
			} catch (SQLException ex) {
				ex.printStackTrace();
			}

			StringBuilder builder = new StringBuilder();
			for (int val : counts) {
				builder.append(val).append(", ");
			}
			LOG.debug("SQL:{} executed. Result:{}", sqlContext.getSqlName(), builder.toString());
		}
		return result;
	}
354470
public List<List<Object>> queryResults(String sql, String[] args,
			GeoPackageDataType[] dataTypes) {
		return db.queryResults(sql, args, dataTypes);
	}
609880
public <T> T executeQuery(@NotNull ResultSetProcessor<T> processor, @NotNull @SQL String sql, Object... args) {
        return executeQuery(processor, SqlQuery.query(sql, args));
    }
96977
public void findStream(String sql, Object []args, ResultStream<Cursor> result)
  {
    QueryBuilderKraken builder = QueryParserKraken.parse(this, sql);
    
    if (builder.isTableLoaded()) {
      QueryKraken query = builder.build(); 
      
      findStream(query, args, result);
    }
    else {
      String tableName = builder.getTableName();
      
      _tableService.loadTable(tableName,
                              result.of((x,r)->{
                                findStream(builder.build(), args, r); 
                              }));
                      //new FindStreamResult(result, builder, args));
    }
  }
353502
public static <T> List<T> queryForList(String sql, Class<T> clz, Object... args) {
		List<T> result = new ArrayList<T>();
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			con = getconnnection();
			ps = con.prepareStatement(sql);
			if (args != null) {
				for (int i = 0; i < args.length; i++) {
					ps.setObject((i + 1), args[i]);
				}
			}
			rs = ps.executeQuery();
			ResultSetMetaData rsmd = rs.getMetaData();
			int columnCount = rsmd.getColumnCount();
			while (rs.next()) {
				T obj = clz.newInstance();
				for (int i = 1; i <= columnCount; i++) {
					String columnName = rsmd.getColumnName(i);
					String methodName = "set" + columnName.substring(0, 1).toUpperCase()
							+ columnName.substring(1, columnName.length());
					Method method[] = clz.getMethods();
					for (Method meth : method) {
						if (methodName.equals(meth.getName())) {
							meth.invoke(obj, rs.getObject(i));
						}
					}
				}
				result.add(obj);
			}
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} finally {
			close(rs, ps, con);
		}
		return result;
	}
1226626
public <T> T querySingleTypedResult(String sql, String[] args) {
		@SuppressWarnings("unchecked")
		T result = (T) querySingleResult(sql, args);
		return result;
	}
425305
public SqlStatement parse(String sql) {

        // does a cached parse result exist for this statement?
        if (_cachedSqlStatements.containsKey(sql)) {
            return _cachedSqlStatements.get(sql);
        }

        SqlGrammar _parser = new SqlGrammar(new StringReader(sql));
        SqlStatement parsed = null;
        try {
            parsed = _parser.parse();
        } catch (ParseException e) {
            throw new ControlException("Error parsing SQL statment." + e.getMessage(), e);
        } catch (TokenMgrError tme) {
            throw new ControlException("Error parsing SQL statment. " + tme.getMessage(), tme);
        }

        if (parsed.isCacheable()) {
            _cachedSqlStatements.put(sql, parsed);
        }
        return parsed;
    }
1094228
private void get(final StringBuilder sql) {
        sql.append("SELECT * FROM ").append(getName()).append(" WHERE ").append(JdbcRepositories.getDefaultKeyName()).append(" = ?");
    }
418250
protected <T> CompletableFuture<ResultSet> executeQuery(final EntityInfo<T> info, final AsyncConnection conn, final String sql) {
        final byte[] bytes = conn.getAttribute(CONN_ATTR_BYTESBAME);
        final ByteBufferWriter writer = ByteBufferWriter.create(bufferPool);
        {
            writer.put((byte) 'Q');
            int start = writer.position();
            writer.putInt(0);
            writeUTF8String(writer, sql);
            writer.putInt(start, writer.position() - start);
        }
        final ByteBuffer[] buffers = writer.toBuffers();
        final CompletableFuture<ResultSet> future = new CompletableFuture();
        conn.write(buffers, buffers, new CompletionHandler<Integer, ByteBuffer[]>() {
            @Override
            public void completed(Integer result, ByteBuffer[] attachment1) {
                if (result < 0) {
                    failed(new SQLException("Write Buffer Error"), attachment1);
                    return;
                }
                int index = -1;
                for (int i = 0; i < attachment1.length; i++) {
                    if (attachment1[i].hasRemaining()) {
                        index = i;
                        break;
                    }
                    bufferPool.accept(attachment1[i]);
                }
                if (index == 0) {
                    conn.write(attachment1, attachment1, this);
                    return;
                } else if (index > 0) {
                    ByteBuffer[] newattachs = new ByteBuffer[attachment1.length - index];
                    System.arraycopy(attachment1, index, newattachs, 0, newattachs.length);
                    conn.write(newattachs, newattachs, this);
                    return;
                }
                final PgResultSet resultSet = new PgResultSet();
                final List<ByteBuffer> readBuffs = new ArrayList<>();
                conn.read(new CompletionHandler<Integer, ByteBuffer>() {
                    @Override
                    public void completed(Integer result, ByteBuffer attachment2) {
                        if (result < 0) {
                            failed(new SQLException("Read Buffer Error"), attachment2);
                            return;
                        }
                        if (result == 8192 || !attachment2.hasRemaining()) { //postgresql数据包上限为8192 还有数据
                            attachment2.flip();
                            readBuffs.add(attachment2);
                            conn.read(this);
                            return;
                        }
                        attachment2.flip();
                        readBuffs.add(attachment2);
                        final ByteBufferReader buffer = ByteBufferReader.create(readBuffs);
                        boolean endok = false;
                        boolean futureover = false;
                        while (buffer.hasRemaining()) {
                            final char cmd = (char) buffer.get();
                            int length = buffer.getInt();
                            switch (cmd) {
                                case 'E':
                                    byte[] field = new byte[255];
                                    String level = null,
                                     code = null,
                                     message = null;
                                    for (byte type = buffer.get(); type != 0; type = buffer.get()) {
                                        String value = readUTF8String(buffer, field);
                                        if (type == (byte) 'S') {
                                            level = value;
                                        } else if (type == 'C') {
                                            code = value;
                                        } else if (type == 'M') {
                                            message = value;
                                        }
                                    }
                                    future.completeExceptionally(new SQLException(message, code, 0));
                                    futureover = true;
                                    break;
                                case 'T':
                                    RowDesc rowDesc = new RespRowDescDecoder().read(buffer, length, bytes);
                                    resultSet.setRowDesc(rowDesc);
                                    break;
                                case 'D':
                                    RowData rowData = new RespRowDataDecoder().read(buffer, length, bytes);
                                    resultSet.addRowData(rowData);
                                    futureover = true;
                                    break;
                                case 'Z':
                                    //buffer.position(buffer.position() + length - 4);
                                    buffer.skip(length - 4);
                                    endok = true;
                                    break;
                                default:
                                    //buffer.position(buffer.position() + length - 4);
                                    buffer.skip(length - 4);
                                    break;
                            }
                        }
                        for (ByteBuffer buf : readBuffs) {
                            bufferPool.accept(buf);
                        }
                        if (!futureover) future.completeExceptionally(new SQLException("SQL(" + sql + ") executeQuery error"));
                        if (endok) {
                            readPool.offerConnection(conn);
                            future.complete(resultSet);
                        } else {
                            conn.dispose();
                        }
                    }

                    @Override
                    public void failed(Throwable exc, ByteBuffer attachment2) {
                        //不用bufferPool.accept
                        future.completeExceptionally(exc);
                        conn.dispose();
                    }
                });
            }

            @Override
            public void failed(Throwable exc, ByteBuffer[] attachment1) {
                for (ByteBuffer attach : attachment1) {
                    bufferPool.accept(attach);
                }
                future.completeExceptionally(exc);
            }
        });
        return future;
    }
302895
public void findAllLocal(String sql, Object []args, Result<Iterable<Cursor>> result)
  {
    QueryBuilderKraken builder = QueryParserKraken.parse(this, sql);
    
    QueryKraken query = builder.build(); 
      
    TableKraken table = query.table();
    TableKelp tableKelp = table.getTableKelp();

    RowCursor cursor = tableKelp.cursor();

    query.fillKey(cursor, args);
    
    query.findAllLocal(result, args);
  }
1129433
protected void execute(String sqlStatement, PrintWriter out, boolean acceptFailure) throws Exception {

        try (Connection conn = dataSource.getConnection()) {
            try (Statement stmt = conn.createStatement()) {

                boolean success = execute(stmt, sqlStatement, out, acceptFailure);

                // Loop over all kinds of results.
                while (success) { /* 'success' is not modified below this line */
                    int rowCount = stmt.getUpdateCount();

                    if (rowCount > 0) {
                        // --------------------------------------------------
                        // Result of successful INSERT or UPDATE or the like
                        // --------------------------------------------------
                        if (options.debug) {
                            out.println("Rows affected: " + rowCount);
                            out.flush();
                        }

                        if (stmt.getMoreResults()) {
                            continue;
                        }

                    } else if (rowCount == 0) {
                        // --------------------------------------------------
                        // Either a DDL command or 0 updates
                        // --------------------------------------------------
                        if (options.debug) {
                            out.println("No rows affected or statement was DDL command");
                            out.flush();
                        }

                        boolean moreResults;
                        try {
                            moreResults = stmt.getMoreResults();
                        } catch (SQLException sqle) {

                            // State: 24000 - Invalid cursor state
                            //  [Teradata: Continue request submitted but no response to return]
                            if (sqle.getSQLState().startsWith("24")) {
                                break;

                            } else {
                                throw sqle;
                            }
                        }
                        if (moreResults) {
                            continue;
                        }

                    } else { // rowCount < 0
                        // --------------------------------------------------
                        // Either we have a result set or no more results...
                        // --------------------------------------------------
                        ResultSet rs = stmt.getResultSet();
                        if (null != rs) {
                            // Ignore resultset
                            rs.close();

                            if (stmt.getMoreResults()) {
                                continue;
                            }
                        }
                    }

                    // No more results
                    break;
                }
            }
        } catch (SQLException sqle) {
            out.println("Failed to execute statement: \n" + sqlStatement);
            out.println("\n\nDescription of failure: \n" + Database.squeeze(sqle));
            out.flush();
            throw sqle;

        } catch (Exception e) {
            out.println("Failed to execute statement: \n" + sqlStatement);
            out.println("\n\nDescription of failure: \n" + e.getMessage());
            out.flush();
            throw e;
        }
    }
351211
public <T> List<T> query(String sql, RowMapper<T> rowMapper) throws SQLException{
		if (logger.isDebugEnabled()) {
			logger.debug("Executing SQL statement [" + sql + "]");
		}
		
		Connection connection = null;
		Statement stm = null;
		ResultSet rs = null;
		
		ArrayList<T> result = new ArrayList<T>();
		
		try{
			connection = ds.getConnection();
			stm = connection.createStatement();			
			rs = stm.executeQuery(sql);
			
			while(rs.next()){
				result.add( rowMapper.map(rs) );
			}
			
		} catch (SQLException e) {
			throw e;
		}finally{
			if(rs!=null) rs.close();
			if(stm!=null) stm.close();
			if(connection!=null) connection.close();			
		}
		
		return result;
	}