Java 类java.sql.ResultSet 实例源码

项目:java-swing-template    文件:UserModel.java   
public static ArrayList<Privilege> getAssignedUserPrivileges(User u) throws Exception {
    ArrayList<Privilege> al = new ArrayList<>();
    String query = "SELECT system_privileges.prv_id, system_privileges.prv_code, "
            + "system_privileges.prv_name, system_privileges.prv_display_name, system_privileges.prv_parent "
            + "FROM user_privileges "
            + "INNER JOIN system_privileges ON user_privileges.prv_id = system_privileges.prv_id "
            + "WHERE user_privileges.user_id = ?";
    PreparedStatement ps = con.prepareStatement(query);
    ps.setInt(1, u.getUserId());
    ResultSet rs = ps.executeQuery();
    while (rs.next()) {
        Privilege sp = new Privilege();
        sp.setPrvId(rs.getInt("prv_id"));
        sp.setPrvCode(rs.getString("prv_code"));
        sp.setPrvName(rs.getString("prv_name"));
        sp.setPrvDisplayName(rs.getString("prv_display_name"));
        sp.setPrvParent(rs.getInt("prv_parent"));
        al.add(sp);
    }
    return al;
}
项目:rapidminer    文件:DatabaseHandler.java   
public static List<Attribute> createAttributes(ResultSet rs) throws SQLException {
    LinkedList attributes = new LinkedList();
    if(rs == null) {
        throw new IllegalArgumentException("Cannot create attributes: ResultSet must not be null!");
    } else {
        ResultSetMetaData metadata;
        try {
            metadata = rs.getMetaData();
        } catch (NullPointerException var7) {
            throw new RuntimeException("Could not create attribute list: ResultSet object seems closed.");
        }

        int numberOfColumns = metadata.getColumnCount();

        for(int column = 1; column <= numberOfColumns; ++column) {
            String name = metadata.getColumnLabel(column);
            Attribute attribute = AttributeFactory.createAttribute(name, getRapidMinerTypeIndex(metadata.getColumnType(column)));
            attributes.add(attribute);
        }

        return attributes;
    }
}
项目:jdbacl    文件:ResultSetDataIterator.java   
@Override
public DataContainer<ResultSet> next(DataContainer<ResultSet> container) {
       LOGGER.debug("next() called on {}", this);
       if (resultSet == null)
        return null;
    try {
        if (resultSet.next()) {
            return container.setData(resultSet);
        } else {
            IOUtil.close(this);
            return null;
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}
项目:OpenVertretung    文件:CallableStatement.java   
@SuppressWarnings("synthetic-access")
CallableStatementParamInfo(java.sql.ResultSet paramTypesRs) throws SQLException {
    boolean hadRows = paramTypesRs.last();

    this.nativeSql = CallableStatement.this.originalSql;
    this.catalogInUse = CallableStatement.this.currentCatalog;
    this.isFunctionCall = CallableStatement.this.callingStoredFunction;

    if (hadRows) {
        this.numParameters = paramTypesRs.getRow();

        this.parameterList = new ArrayList<CallableStatementParam>(this.numParameters);
        this.parameterMap = new HashMap<String, CallableStatementParam>(this.numParameters);

        paramTypesRs.beforeFirst();

        addParametersFromDBMD(paramTypesRs);
    } else {
        this.numParameters = 0;
    }

    if (this.isFunctionCall) {
        this.numParameters += 1;
    }
}
项目:uclan-messanger    文件:AuthenticationProvider.java   
public User registerUser(User user) throws Exception {
    try {            
        connect();
        String sql = String.format("CALL register_user('%s', '%s', '%s');", user.getUserName(), user.getEmail(), user.getPassword());                        
        statement = connection.createStatement();            
        ResultSet resultSet = statement.executeQuery(sql);            
        if(resultSet.first()) {
            user.setId(resultSet.getInt("Id"));

        } else {
            user = null;
        }            
        disconnect();
        return user;
    } catch (Exception e) {
        throw new Exception("error occured while saving the user data!");
    }
}
项目:morf    文件:TestSqlStatements.java   
/**
 * Tests the select order by statement (with nulls last) against all {@linkplain SqlDialect}s
 *
 * @throws SQLException in case of error.
 */
@Test
public void testSelectFirstOrderByNullsLastGetUndocumentedResult() throws SQLException {
  SelectFirstStatement selectOrderByNullsLastStat = selectFirst( field("field2")).from(tableRef("OrderByNullsLastTable")).orderBy(field("field1").desc().nullsLast());

  String sql = convertStatementToSQL(selectOrderByNullsLastStat);

  sqlScriptExecutorProvider.get().executeQuery(sql, new ResultSetProcessor<Void>() {

    @Override
    public Void process(ResultSet resultSet) throws SQLException {
      List<String> expectedResultField2 = Lists.newArrayList("3","4");
      assertTrue(resultSet.next());
      assertTrue(expectedResultField2.contains(resultSet.getString(1)));
      assertFalse(resultSet.next());
      return null;
    };
  });
}
项目:org.mybatis.generator.core-1.3.5    文件:DatabaseIntrospector.java   
/**
 * This method calls database metadata to retrieve some extra information about the table
 * such as remarks associated with the table and the type.
 * 
 * If there is any error, we just add a warning and continue.
 * 
 * @param introspectedTable
 */
private void enhanceIntrospectedTable(IntrospectedTable introspectedTable) {
    try {
        FullyQualifiedTable fqt = introspectedTable.getFullyQualifiedTable();

        ResultSet rs = databaseMetaData.getTables(fqt.getIntrospectedCatalog(), fqt.getIntrospectedSchema(),
                fqt.getIntrospectedTableName(), null);
        if (rs.next()) {
            String remarks = rs.getString("REMARKS"); //$NON-NLS-1$
            String tableType = rs.getString("TABLE_TYPE"); //$NON-NLS-1$
            introspectedTable.setRemarks(remarks);
            introspectedTable.setTableType(tableType);
        }
        closeResultSet(rs);
    } catch (SQLException e) {
        warnings.add(getString("Warning.27", e.getMessage())); //$NON-NLS-1$
    }
}
项目:Spring-5.0-Cookbook    文件:LoginDaoImpl.java   
@Override
public List<RolePermission> getUserGrantedAuthority(int userId) {
    String sql = "SELECT * FROM role_permission WHERE userId=?";
    List<RolePermission> roleperms = jdbcInsert.getJdbcTemplate().query(sql, new Object[]{userId}, new RowMapper<RolePermission>() {

        @Override
        public RolePermission mapRow(ResultSet rs, int rowNum) throws SQLException {
            RolePermission roleperm = new RolePermission();
            roleperm.setId(rs.getInt("id"));
            roleperm.setRoleId(rs.getInt("roleId"));
            roleperm.setPermissionId(rs.getInt("permissionId"));
            roleperm.setUserId(rs.getInt("userId"));

            return roleperm;
        }
    });
    return roleperms;
}
项目:holon-jdbc    文件:TestEnableDataSourceTomcat.java   
@Test
public void testDataSource() throws SQLException {

    assertNotNull(dataSource);

    assertTrue(dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource);

    try (Connection c = dataSource.getConnection()) {
        assertNotNull(c);

        try (ResultSet rs = c.createStatement().executeQuery("select str from testx where key=1")) {
            rs.next();
            assertEquals("One", rs.getString(1));
        }
    }

}
项目:uroborosql    文件:AuditLogSqlFilterTest.java   
@Test
public void testExecuteQueryFilter() throws Exception {
    cleanInsert(Paths.get("src/test/resources/data/setup", "testExecuteQuery.ltsv"));

    List<String> log = TestAppender.getLogbackLogs(() -> {
        SqlContext ctx = agent.contextFrom("example/select_product")
                .paramList("product_id", new BigDecimal("0"), new BigDecimal("2"))
                .param("_userName", "testUserName").param("_funcId", "testFunction").setSqlId("111");
        ctx.setResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE);

        agent.query(ctx);
    });

    assertThat(log, is(Files.readAllLines(
            Paths.get("src/test/resources/data/expected/AuditLogSqlFilter", "testExecuteQueryFilter.txt"),
            StandardCharsets.UTF_8)));
}
项目:Java-Air-Reservation    文件:FlightLeg.java   
public ResultSet getFromTo(String pfrom_ap,String pto_ap) {
    PreparedStatement pst;
    try {
        String sql = "SELECT * FROM `flight_leg` WHERE `from_aID` = ? AND `to_aID` = ?";
        pst = this.conn.prepareStatement(sql);
        pst.setString(1, pfrom_ap);
        pst.setString(2, pto_ap);
        ResultSet rs;
        rs = pst.executeQuery();
        return rs;
    } catch (SQLException e) {
        System.out.println("Error : while excicuting prepared statement");
        System.out.println(e);
        return null;
    }
}
项目:lams    文件:ToolDBDeployTask.java   
private long getNewToolContentId(long newToolId, Connection conn) throws DeployException {
PreparedStatement stmt = null;
ResultSet results = null;
try {
    stmt = conn.prepareStatement("INSERT INTO lams_tool_content (tool_id) VALUES (?)");
    stmt.setLong(1, newToolId);
    stmt.execute();
    stmt = conn.prepareStatement("SELECT LAST_INSERT_ID() FROM lams_tool_content");
    results = stmt.executeQuery();
    if (results.next()) {
    return results.getLong("LAST_INSERT_ID()");
    } else {
    throw new DeployException("No tool content id found");
    }

} catch (SQLException sqlex) {
    throw new DeployException("Could not get new tool content id", sqlex);
} finally {
    DbUtils.closeQuietly(stmt);
    DbUtils.closeQuietly(results);
}
   }
项目:Equella    文件:SqlTaxonomyDataSource.java   
private Object executeSingleResultQuery(String query, Map<?, ?> params)
{
    return jdbcTemplate.query(query, params, new ResultSetExtractor()
    {
        @Override
        public Object extractData(ResultSet rs) throws SQLException, DataAccessException
        {
            Object data = null;
            if( rs.next() )
            {
                data = rs.getObject(1);

                // Sanity check - ensure only a single result
                if( rs.next() )
                {
                    throw new IncorrectResultSizeDataAccessException(1);
                }
            }
            return data;
        }
    });
}
项目:Spring-5.0-Cookbook    文件:LoginDaoImpl.java   
@Override
public List<Permission> getPermissions() {
    String sql = "SELECT * FROM permission";
    List<Permission> perms = jdbcInsert.getJdbcTemplate().query(sql,  new RowMapper<Permission>() {

        @Override
        public Permission mapRow(ResultSet rs, int rowNum) throws SQLException {
            Permission perm = new Permission();
            perm.setId(rs.getInt("id"));
            perm.setName(rs.getString("name"));
            perm.setDescription(rs.getString("description"));

            return perm;
        }
    });

    return perms;
}
项目:Java-9-Cookbook    文件:Chapter06Database01.java   
private static void demo3_execute_insert(){
    executeUpdate("delete from enums where id < 7"); //to make the demo re-runnable

    System.out.println();
    try (Connection conn = getDbConnection()) {
        try (Statement st = conn.createStatement()) {
            boolean res = st.execute("insert into enums (id, type, value) values(1,'vehicle','car')");
            if (res) {
                ResultSet rs = st.getResultSet();
                while (rs.next()) {
                    int id = rs.getInt(1); //More efficient than rs.getInt("id")
                    String type = rs.getString(2);
                    String value = rs.getString(3);
                    System.out.println("id = " + id + ", type = " + type + ", value = " + value);
                }
            } else {
                int count = st.getUpdateCount();
                System.out.println("Update count = " + count);
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
项目:incubator-netbeans    文件:DefaultAdaptor.java   
/**
* Gets a description of the stored procedures available in a
* catalog.
*/
public ResultSet getProcedures(String catalog, String schemaPattern, String procedureNamePattern) throws SQLException
{
    if (getCapitializeUsername() && schemaPattern != null) schemaPattern = schemaPattern.toUpperCase();
    String query = (String)properties.get(PROP_PROCEDURES_QUERY);
    if (query != null) {
        if (con != null) {
            PreparedStatement stmt = con.prepareStatement(query);
            stmt.setString(1, catalog);
            stmt.setString(2, schemaPattern);
            stmt.setString(3, procedureNamePattern);
            return stmt.executeQuery();
        } else throw new SQLException(bundle.getString("EXC_NoConnection")); // NOI18N
    }

    if (dmd == null) throw new SQLException(bundle.getString("EXC_NoDBMetadata")); // NOI18N
    return dmd.getProcedures(catalog, schemaPattern, procedureNamePattern);
}
项目:springboot-shiro-cas-mybatis    文件:InspektrThrottledSubmissionByIpAddressAndUsernameHandlerInterceptorAdapter.java   
@Override
protected boolean exceedsThreshold(final HttpServletRequest request) {
    final String query = "SELECT AUD_DATE FROM COM_AUDIT_TRAIL WHERE AUD_CLIENT_IP = ? AND AUD_USER = ? "
            + "AND AUD_ACTION = ? AND APPLIC_CD = ? AND AUD_DATE >= ? ORDER BY AUD_DATE DESC";
    final String userToUse = constructUsername(request, getUsernameParameter());
    final Calendar cutoff = Calendar.getInstance();
    cutoff.add(Calendar.SECOND, -1 * getFailureRangeInSeconds());
    final List<Timestamp> failures = this.jdbcTemplate.query(
            query,
            new Object[] {request.getRemoteAddr(), userToUse, this.authenticationFailureCode, this.applicationCode, cutoff.getTime()},
            new int[] {Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.TIMESTAMP},
            new RowMapper<Timestamp>() {
                @Override
                public Timestamp mapRow(final ResultSet resultSet, final int i) throws SQLException {
                    return resultSet.getTimestamp(1);
                }
            });
    if (failures.size() < 2) {
        return false;
    }
    // Compute rate in submissions/sec between last two authn failures and compare with threshold
    return NUMBER_OF_MILLISECONDS_IN_SECOND / (failures.get(0).getTime() - failures.get(1).getTime()) > getThresholdRate();
}
项目:Lucid2.0    文件:MapleCharacter.java   
public void showNote() {
    try {
        Connection con = DatabaseConnection.getConnection();
        try (PreparedStatement ps = con.prepareStatement("SELECT * FROM notes WHERE `to`=?", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) {
            ps.setString(1, getName());
            try (ResultSet rs = ps.executeQuery()) {
                rs.last();
                int count = rs.getRow();
                rs.first();
                client.getSession().write(CSPacket.showNotes(rs, count));
            }
        }
    } catch (SQLException e) {
        System.err.println("Unable to show note" + e);
    }
}
项目:vertx-generator    文件:ConfigUtil.java   
/**
 * 保存实体类配置文件信息
 * 
 * @param Config
 * @throws Exception
 */
public static int saveClassConfig(ClassConfig config, String name) throws Exception {
    Connection conn = null;
    Statement stat = null;
    ResultSet rs = null;
    try {
        conn = getConnection();
        stat = conn.createStatement();
        String jsonStr = JSON.toJSONString(config);
        String sql = String.format("replace into ClassConfig(name,value) values('%s', '%s')", name, jsonStr);
        int result = stat.executeUpdate(sql);
        return result;
    } finally {
        if (rs != null)
            rs.close();
        if (stat != null)
            stat.close();
        if (conn != null)
            conn.close();
    }
}
项目:SistemaAlmoxarifado    文件:EmpenhoEntradaDAO.java   
public static ArrayList<EmpenhoEntrada> retreaveAll() throws SQLException {
    Statement stm
            = Database.createConnection().
                    createStatement();
    String sql = "SELECT * FROM empenhos_entradas";
    ResultSet rs = stm.executeQuery(sql);
    ArrayList<EmpenhoEntrada> eie = new ArrayList<>();
    while (rs.next()) {
        eie.add(new EmpenhoEntrada(
                rs.getInt("id"),
                rs.getInt("empenho"),
                rs.getInt("entrada")));
    }
    rs.next();
    return eie;
}
项目:bdf2    文件:LobStoreServiceImpl.java   
public String getString(String id) throws SQLException {
    final String sql = "SELECT CONTENT_ FROM BDF2_CLOB_STORE WHERE ID_=?";
    List<String> list = super.getJdbcTemplate().query(sql, new Object[]{id}, new RowMapper<String>() {
        public String mapRow(ResultSet resultset, int i)
                throws SQLException {
            String content = LobStoreServiceImpl.this
                    .getLobHandler().getClobAsString(resultset, 1);
            return content;
        }
    });
    if(list.size() > 0){
        return list.get(0);
    }else{
        return null;
    }
}
项目:calcite-avatica    文件:RemoteDriverTest.java   
@Test public void testPrepareBindExecuteFetchVarbinary() throws Exception {
  ConnectionSpec.getDatabaseLock().lock();
  try {
    final Connection connection = getLocalConnection();
    final String sql = "select x'de' || ? as c from (values (1, 'a'))";
    final PreparedStatement ps =
        connection.prepareStatement(sql);
    final ParameterMetaData parameterMetaData = ps.getParameterMetaData();
    assertThat(parameterMetaData.getParameterCount(), equalTo(1));

    ps.setBytes(1, new byte[]{65, 0, 66});
    final ResultSet resultSet = ps.executeQuery();
    assertTrue(resultSet.next());
    assertThat(resultSet.getBytes(1),
        equalTo(new byte[]{(byte) 0xDE, 65, 0, 66}));
    resultSet.close();
    ps.close();
    connection.close();
  } finally {
    ConnectionSpec.getDatabaseLock().unlock();
  }
}
项目:Homework    文件:JDBCEx05.java   
public int delete(Emp emp)
{   
    if(null != findEmp(emp.getEmpno()))
    {
        ResultSet rs = null;    
        String fsql = "DELETE FROM emp WHERE empno = %s";
        String sql = String.format(fsql, emp.getEmpno());

        rs = getResultSet(sql);

        return 1;
    }
    else
    {
        return 0;
    }
}
项目:adept    文件:ArrayHandler.java   
/**
 * 将'ResultSet'结果集的第一行数据转换为'对象数组'.
 * @param rs ResultSet实例
 * @return 对象数组
 */
@Override
public Object[] transform(ResultSet rs) {
    if (rs == null) {
        return null;
    }

    try {
        // 获取Resultset元数据和查询的列数.
        ResultSetMetaData rsmd = rs.getMetaData();
        int cols = rsmd.getColumnCount();

        // 初始化列数长度的数组,将第一行各列的数据存到'对象数组'中.
        if (rs.next()) {
            Object[] objArr = new Object[cols];
            for (int i = 0; i < cols; i++)  {
                objArr[i] = rs.getObject(i + 1);
            }
            return objArr;
        }
    } catch (Exception e) {
        throw new ResultsTransformException("将'ResultSet'结果集转换为'对象数组'出错!", e);
    }

    return null;
}
项目:s-store    文件:JDBC4DatabaseMetaData.java   
/**
 * Retrieves a description of the foreign key columns that reference the
 * given table's primary key columns (the foreign keys exported by a table).
 */
@Override
public ResultSet getExportedKeys(String catalog, String schema, String table) throws SQLException
{
    checkClosed();
    VoltTable vtable = new VoltTable(
            new ColumnInfo("PKTABLE_CAT", VoltType.STRING),
            new ColumnInfo("PKTABLE_SCHEM", VoltType.STRING),
            new ColumnInfo("PKTABLE_NAME", VoltType.STRING),
            new ColumnInfo("PKCOLUMN_NAME", VoltType.STRING),
            new ColumnInfo("FKTABLE_CAT", VoltType.STRING),
            new ColumnInfo("FKTABLE_SCHEM", VoltType.STRING),
            new ColumnInfo("FKTABLE_NAME", VoltType.STRING),
            new ColumnInfo("FKCOLUMN_NAME", VoltType.STRING),
            new ColumnInfo("KEY_SEQ", VoltType.SMALLINT),
            new ColumnInfo("UPDATE_RULE", VoltType.SMALLINT),
            new ColumnInfo("DELETE_RULE", VoltType.SMALLINT),
            new ColumnInfo("FK_NAME", VoltType.STRING),
            new ColumnInfo("PK_NAME", VoltType.STRING),
            new ColumnInfo("DEFERRABILITY", VoltType.SMALLINT)
    );

    JDBC4ResultSet res = new JDBC4ResultSet(this.sysCatalog, vtable);
    return res;
}
项目:rapidminer    文件:ResultSetExampleSource.java   
public ExampleSet createExampleSet() throws OperatorException {
    int dataRowType = this.getParameterAsInt("datamanagement");
    ResultSet resultSet = this.getResultSet();
    List attributeList = null;

    try {
        attributeList = DatabaseHandler.createAttributes(resultSet);
    } catch (SQLException var6) {
        throw new UserError(this, var6, 304, new Object[]{var6.getMessage()});
    }

    this.setNominalValues(attributeList, resultSet, find(attributeList, this.getParameterAsString("label_attribute")));
    ResultSetDataRowReader reader = new ResultSetDataRowReader(new DataRowFactory(dataRowType, '.'), attributeList, resultSet);
    MemoryExampleTable table = new MemoryExampleTable(attributeList, reader);
    this.tearDown();
    return createExampleSet(table, this);
}
项目:mongodb-rdbms-sync    文件:O2MEventDistributorNew.java   
private RowId createSubEvents(final String query, RowId rid, String tableName, boolean isChildQuery) throws SyncError {
    logger.info("createSubEvents called with parameters : isChildQuery =" + isChildQuery + " , rid = " + rid
            + " , tableName = " + tableName + " , query = " + query);
    PreparedStatement rowIdpstmt = null;
    ResultSet rowIdSet = null;
    RowId maxRid = null;
    RowId minRid = null;
    try {
        rowIdpstmt = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT);
        if (isChildQuery) {
            rowIdpstmt.setRowId(1, rid);
        }
        rowIdpstmt.setFetchSize(5000);
        rowIdSet = rowIdpstmt.executeQuery();
        rowIdSet.next();
        minRid = rowIdSet.getRowId(1);
        for (++subEventCount; subEventCount < (degree - 1); subEventCount++) {
            rowIdSet.relative((int) optimalRange);
            maxRid = rowIdSet.getRowId(1);
            getSubEvent(minRid, maxRid, false);
            minRid = maxRid;
            fetchCount += optimalRange;
            if (fetchCount > 1000000L) {
                break;
            }
        }
        if (subEventCount == (degree - 1)) {
            rowIdSet.last();
            maxRid = rowIdSet.getRowId(1);
            getSubEvent(minRid, maxRid, true);
            logger.info("Total subEvents created :" + eventCount);
        }
    } catch (Exception e) {
        logger.error("Error while creating subEvents ", e);
        throw new SyncError(e);
    } finally {
        DbResourceUtils.closeResources(rowIdSet, rowIdpstmt, null);
    }
    return maxRid;
}
项目:xvms    文件:MysqlTool.java   
/**
 * 返回数据资源句柄 要记得关闭  用于多条数据的提取
 * @param sqlStatement
 * @return
 */
public ResultSet query(String sqlStatement){
    try{
        rs = st.executeQuery(sqlStatement);
        if(rs!=null){
           return rs;
        }else{
           return null;
        }
    }catch(Exception e){
       log.error("查询失败"+e.toString());
        return null;
    }
}
项目:elastic-db-tools-for-java    文件:Program.java   
private static int getNumCompletedDatabaseCreations(Connection conn,
        String db) throws SQLException {
    Statement cmd = conn.createStatement();
    ResultSet resultSet = cmd.executeQuery("SELECT COUNT(*) FROM sys.dm_operation_status \r\n"
            + "WHERE resource_type = 0 -- 'Database' \r\n AND major_resource_id = '" + db + "' \r\n" + "AND state = 2 -- ' COMPLETED'");
    if (resultSet.next()) {
        return resultSet.getInt(1);
    }
    return -1;
}
项目:dev-courses    文件:TestOdbcTypes.java   
public void testBigIntSimpleRead() {
    ResultSet rs = null;
    Statement st = null;
    try {
        st = netConn.createStatement();
        rs = st.executeQuery("SELECT * FROM alltypes WHERE id in (1, 2)");
        assertTrue("Got no rows with id in (1, 2)", rs.next());
        assertEquals(Long.class, rs.getObject("bi").getClass());
        assertTrue("Got only one row with id in (1, 2)", rs.next());
        assertEquals(6, rs.getLong("bi"));
        assertFalse("Got too many rows with id in (1, 2)", rs.next());
    } catch (SQLException se) {
        junit.framework.AssertionFailedError ase
            = new junit.framework.AssertionFailedError(se.getMessage());
        ase.initCause(se);
        throw ase;
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
            if (st != null) {
                st.close();
            }
        } catch(Exception e) {
        }
    }
}
项目:dremio-oss    文件:DremioResultSetTest.java   
@Test
public void test_next_blocksFurtherAccessAfterEnd()
    throws SQLException
{
  Connection connection =
      new Driver().connect( "jdbc:dremio:zk=local", JdbcAssert.getDefaultProperties() );
  Statement statement = connection.createStatement();
  ResultSet resultSet =
      statement.executeQuery( "SELECT 1 AS x \n" +
                              "FROM cp.`donuts.json` \n" +
                              "LIMIT 2" );

  // Advance to first row; confirm can access data.
  assertThat( resultSet.next(), is( true ) );
  assertThat( resultSet.getInt( 1 ), is ( 1 ) );

  // Advance from first to second (last) row, confirming data access.
  assertThat( resultSet.next(), is( true ) );
  assertThat( resultSet.getInt( 1 ), is ( 1 ) );

  // Now advance past last row.
  assertThat( resultSet.next(), is( false ) );

  // Main check:  That row data access methods now throw SQLException.
  try {
    resultSet.getInt( 1 );
    fail( "Didn't get expected SQLException." );
  }
  catch ( SQLException e ) {
    // Expect something like current InvalidCursorStateSqlException saying
    // "Result set cursor is already positioned past all rows."
    assertThat( e, instanceOf( InvalidCursorStateSqlException.class ) );
    assertThat( e.toString(), containsString( "past" ) );
  }
  // (Any other exception is unexpected result.)

  assertThat( resultSet.next(), is( false ) );

  // TODO:  Ideally, test all other accessor methods.
}
项目:the-vigilantes    文件:StatementImpl.java   
public void enableStreamingResults() throws SQLException {
    synchronized (checkClosed().getConnectionMutex()) {
        this.originalResultSetType = this.resultSetType;
        this.originalFetchSize = this.fetchSize;

        setFetchSize(Integer.MIN_VALUE);
        setResultSetType(ResultSet.TYPE_FORWARD_ONLY);
    }
}
项目:jetfuel    文件:ResultsetToEntity.java   
public T process(ResultSet rs) throws SQLException {

        int row = 0;

        // skip offset
        while (row < offset && rs.next())
            row++;

        // checks if an empty element should be returned
        if (!rs.next())
            return null;

        // map columns
        ResultSetMetaData meta = rs.getMetaData();
        int[] ordinals = new int[meta.getColumnCount()];
        for (int i = 0; i < ordinals.length; i++)
            ordinals[i] = aspect.indexOfColumnName(meta.getColumnLabel(i + 1));

        // create entity
        T entity = aspect.newInstance();
        for (int j = 0; j < ordinals.length; j++) {
            if (ordinals[j] >= 0) {
                Object value = rs.getObject(j + 1);
                if (value != null)
                    aspect.setValue(entity, ordinals[j], value);
            }
        }
        return entity;

    }
项目:uavstack    文件:DAOFactory.java   
public Object getResult(ResultSet rs, int columnIndex) throws SQLException {

            java.sql.Timestamp sqlTimestamp = rs.getTimestamp(columnIndex);
            if (rs.wasNull()) {
                return null;
            }
            else {
                return new java.util.Date(sqlTimestamp.getTime());
            }
        }
项目:Elasticsearch    文件:JDBCTest.java   
public void update_object() throws Exception {
    String sql = " update db1.mytable1 set author['age'] = 24 where id = 1";
    int affectRows = stmt.executeUpdate(sql);
    assertEquals(1, affectRows);

    String searchSQL = " select author['age'] from db1.mytable1 WHERE id = 1";
    ResultSet rs = stmt.executeQuery(searchSQL);
    int age = 0;
    while (rs.next()) {
        age = rs.getInt("author['age']");
    }
    assertEquals(24, age);
}
项目:calcite-avatica    文件:JdbcMeta.java   
public MetaResultSet getTablePrivileges(ConnectionHandle ch, String catalog, Pat schemaPattern,
    Pat tableNamePattern) {
  try {
    final ResultSet rs =
        getConnection(ch.id).getMetaData().getTablePrivileges(catalog,
            schemaPattern.s, tableNamePattern.s);
    int stmtId = registerMetaStatement(rs);
    return JdbcResultSet.create(ch.id, stmtId, rs);
  } catch (SQLException e) {
    throw new RuntimeException(e);
  }
}
项目:all-file    文件:File.java   
public void fileToField(ResultSet resultset, String s)
    throws ServletException, IOException, SmartUploadException, SQLException
{
    long l = 0L;
    int i = 0x10000;
    int j = 0;
    int k = m_startData;
    if(resultset == null)
        throw new IllegalArgumentException("The RecordSet cannot be null (1145).");
    if(s == null)
        throw new IllegalArgumentException("The columnName cannot be null (1150).");
    if(s.length() == 0)
        throw new IllegalArgumentException("The columnName cannot be empty (1155).");
    l = BigInteger.valueOf(m_size).divide(BigInteger.valueOf(i)).longValue();
    j = BigInteger.valueOf(m_size).mod(BigInteger.valueOf(i)).intValue();
    try
    {
        for(int i1 = 1; (long)i1 < l; i1++)
        {
            resultset.updateBinaryStream(s, new ByteArrayInputStream(m_parent.m_binArray, k, i), i);
            k = k != 0 ? k : 1;
            k = i1 * i + m_startData;
        }

        if(j > 0)
            resultset.updateBinaryStream(s, new ByteArrayInputStream(m_parent.m_binArray, k, j), j);
    }
    catch(SQLException sqlexception)
    {
        byte abyte0[] = new byte[m_size];
        System.arraycopy(m_parent.m_binArray, m_startData, abyte0, 0, m_size);
        resultset.updateBytes(s, abyte0);
    }
    catch(Exception exception)
    {
        throw new SmartUploadException("Unable to save file in the DataBase (1130).");
    }
}
项目:parabuild-ci    文件:PostgresTransferHelper.java   
String fixupColumnDefRead(TransferTable t, ResultSetMetaData meta,
                          String columnType, ResultSet columnDesc,
                          int columnIndex) throws SQLException {

    String SeqName   = new String("_" + columnDesc.getString(4) + "_seq");
    int    spaceleft = 31 - SeqName.length();

    if (t.Stmts.sDestTable.length() > spaceleft) {
        SeqName = t.Stmts.sDestTable.substring(0, spaceleft) + SeqName;
    } else {
        SeqName = t.Stmts.sDestTable + SeqName;
    }

    String CompareString = "nextval(\'\"" + SeqName + "\"\'";

    if (columnType.indexOf(CompareString) >= 0) {

        // We just found a increment
        columnType = "SERIAL";
    }

    for (int Idx = 0; Idx < Funcs.length; Idx++) {
        String PostgreSQL_func = Funcs[Idx][PostgreSQL];
        int    iStartPos       = columnType.indexOf(PostgreSQL_func);

        if (iStartPos >= 0) {
            String NewColumnType = columnType.substring(0, iStartPos);

            NewColumnType += Funcs[Idx][HSQLDB];
            NewColumnType +=
                columnType.substring(iStartPos
                                     + PostgreSQL_func.length());
            columnType = NewColumnType;
        }
    }

    return (columnType);
}
项目:Campus    文件:EventTrackerDao.java   
public List<Map<String, Object>> getAllEventsInfo() throws SQLException {

        List<Map<String, Object>> lst_events = new ArrayList<>();

        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = "select * from event_info";

        con = DBConnection.getConnection();
        ps = con.prepareStatement(sql);

        rs = ps.executeQuery();

        while (rs.next()) {
            Map<String, Object> eventInfo = new HashMap<String, Object>();

            eventInfo.put("eventd", rs.getInt(1));
            eventInfo.put("latitude", rs.getDouble(2));
            eventInfo.put("Longitude", rs.getDouble(3));

            Timestamp eventEntireDate = rs.getTimestamp(4);
            if (eventEntireDate != null) {
                String eventDateTimeStr = eventEntireDate.toString();

                eventInfo.put("date", eventDateTimeStr.substring(0, 10));
                eventInfo.put("time", eventDateTimeStr.substring(11, eventDateTimeStr.length()));
            }

            eventInfo.put("eventName", rs.getString(5));

            lst_events.add(eventInfo);
        }

        con.close();

        return lst_events;
    }
项目:ramus    文件:IEngineImpl.java   
@Override
public long getElementCountForQualifier(long qialifierId) {
    return (Long) template.queryForObject("SELECT COUNT(*) FROM " + prefix
            + "elements WHERE qualifier_id=?", new RowMapper() {
        @Override
        public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
            return rs.getLong(1);
        }
    }, qialifierId, true);
}