Java Code Examples for java.sql.ResultSet

The following are top voted examples for showing how to use java.sql.ResultSet. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: java-swing-template   File: UserModel.java   View source code 9 votes vote down vote up
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;
}
 
Example 2
Project: rapidminer   File: DatabaseHandler.java   View source code 7 votes vote down vote up
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;
    }
}
 
Example 3
Project: jdbacl   File: ResultSetDataIterator.java   View source code 6 votes vote down vote up
@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);
	}
}
 
Example 4
Project: OpenVertretung   File: CallableStatement.java   View source code 6 votes vote down vote up
@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;
    }
}
 
Example 5
Project: uclan-messanger   File: AuthenticationProvider.java   View source code 6 votes vote down vote up
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!");
    }
}
 
Example 6
Project: morf   File: TestSqlStatements.java   View source code 6 votes vote down vote up
/**
 * 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;
    };
  });
}
 
Example 7
Project: org.mybatis.generator.core-1.3.5   File: DatabaseIntrospector.java   View source code 6 votes vote down vote up
/**
 * 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$
    }
}
 
Example 8
Project: Spring-5.0-Cookbook   File: LoginDaoImpl.java   View source code 6 votes vote down vote up
@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;
}
 
Example 9
Project: holon-jdbc   File: TestEnableDataSourceTomcat.java   View source code 6 votes vote down vote up
@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));
		}
	}

}
 
Example 10
Project: uroborosql   File: AuditLogSqlFilterTest.java   View source code 6 votes vote down vote up
@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)));
}
 
Example 11
Project: Java-Air-Reservation   File: FlightLeg.java   View source code 6 votes vote down vote up
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;
    }
}
 
Example 12
Project: lams   File: ToolDBDeployTask.java   View source code 6 votes vote down vote up
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);
}
   }
 
Example 13
Project: Equella   File: SqlTaxonomyDataSource.java   View source code 6 votes vote down vote up
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;
		}
	});
}
 
Example 14
Project: Spring-5.0-Cookbook   File: LoginDaoImpl.java   View source code 6 votes vote down vote up
@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;
}
 
Example 15
Project: Java-9-Cookbook   File: Chapter06Database01.java   View source code 6 votes vote down vote up
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();
    }
}
 
Example 16
Project: incubator-netbeans   File: DefaultAdaptor.java   View source code 6 votes vote down vote up
/**
* 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);
}
 
Example 17
Project: springboot-shiro-cas-mybatis   File: InspektrThrottledSubmissionByIpAddressAndUsernameHandlerInterceptorAdapter.java   View source code 6 votes vote down vote up
@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();
}
 
Example 18
Project: Lucid2.0   File: MapleCharacter.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 19
Project: vertx-generator   File: ConfigUtil.java   View source code 6 votes vote down vote up
/**
 * 保存实体类配置文件信息
 * 
 * @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();
	}
}
 
Example 20
Project: SistemaAlmoxarifado   File: EmpenhoEntradaDAO.java   View source code 6 votes vote down vote up
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;
}
 
Example 21
Project: bdf2   File: LobStoreServiceImpl.java   View source code 6 votes vote down vote up
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;
	}
}
 
Example 22
Project: calcite-avatica   File: RemoteDriverTest.java   View source code 6 votes vote down vote up
@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();
  }
}
 
Example 23
Project: Homework   File: JDBCEx05.java   View source code 6 votes vote down vote up
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;
	}
}
 
Example 24
Project: adept   File: ArrayHandler.java   View source code 6 votes vote down vote up
/**
 * 将'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;
}
 
Example 25
Project: s-store   File: JDBC4DatabaseMetaData.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 26
Project: rapidminer   File: ResultSetExampleSource.java   View source code 6 votes vote down vote up
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);
}
 
Example 27
Project: mongodb-rdbms-sync   File: O2MEventDistributorNew.java   View source code 5 votes vote down vote up
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;
}
 
Example 28
Project: xvms   File: MysqlTool.java   View source code 5 votes vote down vote up
/**
 * 返回数据资源句柄 要记得关闭  用于多条数据的提取
 * @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;
    }
}
 
Example 29
Project: elastic-db-tools-for-java   File: Program.java   View source code 5 votes vote down vote up
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;
}
 
Example 30
Project: dev-courses   File: TestOdbcTypes.java   View source code 5 votes vote down vote up
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) {
        }
    }
}
 
Example 31
Project: dremio-oss   File: DremioResultSetTest.java   View source code 5 votes vote down vote up
@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.
}
 
Example 32
Project: the-vigilantes   File: StatementImpl.java   View source code 5 votes vote down vote up
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);
    }
}
 
Example 33
Project: jetfuel   File: ResultsetToEntity.java   View source code 5 votes vote down vote up
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;

	}
 
Example 34
Project: uavstack   File: DAOFactory.java   View source code 5 votes vote down vote up
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());
            }
        }
 
Example 35
Project: Elasticsearch   File: JDBCTest.java   View source code 5 votes vote down vote up
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);
}
 
Example 36
Project: calcite-avatica   File: JdbcMeta.java   View source code 5 votes vote down vote up
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);
  }
}
 
Example 37
Project: all-file   File: File.java   View source code 5 votes vote down vote up
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).");
    }
}
 
Example 38
Project: parabuild-ci   File: PostgresTransferHelper.java   View source code 5 votes vote down vote up
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);
}
 
Example 39
Project: Campus   File: EventTrackerDao.java   View source code 5 votes vote down vote up
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;
	}
 
Example 40
Project: ramus   File: IEngineImpl.java   View source code 5 votes vote down vote up
@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);
}