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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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);
}
 
Example 41
Project: OpenVertretung   File: StatementRegressionTest.java   Source Code and License 5 votes vote down vote up
/**
 * Test fix for BUG#3557 -- UpdatableResultSet not picking up default values
 * 
 * @throws Exception
 *             if test fails.
 */
public void testBug3557() throws Exception {
    boolean populateDefaults = ((com.mysql.jdbc.ConnectionProperties) this.conn).getPopulateInsertRowWithDefaultValues();

    try {
        ((com.mysql.jdbc.ConnectionProperties) this.conn).setPopulateInsertRowWithDefaultValues(true);

        this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3557");

        this.stmt.executeUpdate(
                "CREATE TABLE testBug3557 (`a` varchar(255) NOT NULL default 'XYZ', `b` varchar(255) default '123', PRIMARY KEY  (`a`(100)))");

        Statement updStmt = this.conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
        this.rs = updStmt.executeQuery("SELECT * FROM testBug3557");

        assertTrue(this.rs.getConcurrency() == ResultSet.CONCUR_UPDATABLE);

        this.rs.moveToInsertRow();

        assertEquals("XYZ", this.rs.getObject(1));
        assertEquals("123", this.rs.getObject(2));
    } finally {
        ((com.mysql.jdbc.ConnectionProperties) this.conn).setPopulateInsertRowWithDefaultValues(populateDefaults);

        this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3557");
    }
}
 
Example 42
Project: Spring-Security-Third-Edition   File: JdbcEventDao.java   Source Code and License 5 votes vote down vote up
public Event mapRow(ResultSet rs, int rowNum) throws SQLException {
    CalendarUser attendee = ATTENDEE_ROW_MAPPER.mapRow(rs, rowNum);
    CalendarUser owner = OWNER_ROW_MAPPER.mapRow(rs, rowNum);

    Event event = new Event();
    event.setId(rs.getInt("events.id"));
    event.setSummary(rs.getString("events.summary"));
    event.setDescription(rs.getString("events.description"));
    Calendar when = Calendar.getInstance();
    when.setTime(rs.getDate("events.when"));
    event.setWhen(when);
    event.setAttendee(attendee);
    event.setOwner(owner);
    return event;
}
 
Example 43
Project: pgcodekeeper   File: JdbcLoaderBase.java   Source Code and License 5 votes vote down vote up
protected void queryCheckVersion() throws SQLException {
    setCurrentOperation("version checking query");
    try (ResultSet res = statement.executeQuery(JdbcQueries.QUERY_CHECK_VERSION)) {
        while (res.next()) {
            version = res.getInt(VERSION);
        }
    }
}
 
Example 44
Project: BibliotecaPS   File: ConnectionRegressionTest.java   Source Code and License 5 votes vote down vote up
private boolean isResultSetClosedForTestBug69746(ResultSet resultSet) {
    try {
        resultSet.first();
    } catch (SQLException ex) {
        return ex.getMessage().equalsIgnoreCase(Messages.getString("ResultSet.Operation_not_allowed_after_ResultSet_closed_144"));
    }
    return false;
}
 
Example 45
Project: momo-2   File: MacroObject.java   Source Code and License 5 votes vote down vote up
/**
 * Search for macros by user and given guild
 * @param userId UserID to search for
 * @param guildId GuildID to search in
 * @return Null if no results, populated string array of macro names if results
 */
public static String[] searchByUser(String userId, String guildId) {
	Connection conn = null;
	PreparedStatement stmt = null;
	ResultSet rs = null;
	ArrayList<String> toReturn = new ArrayList<String>(10);
	try {
		conn = ConnectionPool.getConnection(guildId);
		String sql = "SELECT macro FROM `discord_macro` WHERE user_id = ?";
		stmt = conn.prepareStatement(sql);
		stmt.setString(1, userId);
		rs = stmt.executeQuery();
		if(!rs.isBeforeFirst())
			return null;
		while(rs.next()) {
			toReturn.add(rs.getString(1));
		}
		return toReturn.toArray(new String[0]);
	} catch(SQLException e) {
		e.printStackTrace();
		return null;
	} finally {
		SQLUtils.closeQuietly(rs);
		SQLUtils.closeQuietly(stmt);
		SQLUtils.closeQuietly(conn);
	}
}
 
Example 46
Project: OpenVertretung   File: ResultSetRegressionTest.java   Source Code and License 5 votes vote down vote up
public void testBug27431() throws Exception {
    createTable("bug27431", "(`ID` int(20) NOT NULL auto_increment, `Name` varchar(255) NOT NULL default '', PRIMARY KEY  (`ID`))");

    this.stmt.executeUpdate("INSERT INTO bug27431 (`ID`, `Name`) VALUES 	(1, 'Lucho'),(2, 'Lily'),(3, 'Kiro')");

    Statement updStmt = this.conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
    this.rs = updStmt.executeQuery("SELECT ID, Name FROM bug27431");

    while (this.rs.next()) {
        this.rs.deleteRow();
    }

    assertEquals(0, getRowCount("bug27431"));
}
 
Example 47
Project: holon-datastore-jdbc   File: JdbcDatastoreUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Get the Java type which corresponds to the SQL type of the table column with given <code>columnName</code> using
 * the JDBC database metadata.
 * @param databaseMetaData Database metadata
 * @param tableName Table name
 * @param columnName Column name
 * @return Column Java type, or <code>null</code> if column was not found
 * @throws SQLException If an error occurred
 */
private static Class<?> getColumnType(DatabaseMetaData databaseMetaData, String tableName, String columnName)
		throws SQLException {
	try (ResultSet rs = databaseMetaData.getColumns(null, null, tableName, columnName)) {
		if (rs.next()) {
			return jdbcTypeToClass(rs.getInt("DATA_TYPE"));
		}
	}
	return null;
}
 
Example 48
Project: elastic-job-cloud   File: JobEventRdbStorage.java   Source Code and License 5 votes vote down vote up
private void createJobExecutionTableAndIndexIfNeeded(final Connection conn) throws SQLException {
    DatabaseMetaData dbMetaData = conn.getMetaData();
    try (ResultSet resultSet = dbMetaData.getTables(null, null, TABLE_JOB_EXECUTION_LOG, new String[]{"TABLE"})) {
        if (!resultSet.next()) {
            createJobExecutionTable(conn);
        }
    }
}
 
Example 49
Project: ProyectoPacientes   File: BaseTestCase.java   Source Code and License 5 votes vote down vote up
protected int getRowCount(String tableName) throws SQLException {
    ResultSet countRs = null;

    try {
        countRs = this.stmt.executeQuery("SELECT COUNT(*) FROM " + tableName);

        countRs.next();

        return countRs.getInt(1);
    } finally {
        if (countRs != null) {
            countRs.close();
        }
    }
}
 
Example 50
Project: lams   File: CompositeCustomType.java   Source Code and License 5 votes vote down vote up
public Object nullSafeGet(
	ResultSet rs,
	String columnName,
	SessionImplementor session,
	Object owner)
	throws HibernateException, SQLException {

	return userType.nullSafeGet( rs, new String[] {columnName}, session, owner );
}
 
Example 51
Project: lams   File: OracleJdbc4NativeJdbcExtractor.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public OracleJdbc4NativeJdbcExtractor() {
	try {
		setConnectionType((Class<Connection>) getClass().getClassLoader().loadClass("oracle.jdbc.OracleConnection"));
		setStatementType((Class<Statement>) getClass().getClassLoader().loadClass("oracle.jdbc.OracleStatement"));
		setPreparedStatementType((Class<PreparedStatement>) getClass().getClassLoader().loadClass("oracle.jdbc.OraclePreparedStatement"));
		setCallableStatementType((Class<CallableStatement>) getClass().getClassLoader().loadClass("oracle.jdbc.OracleCallableStatement"));
		setResultSetType((Class<ResultSet>) getClass().getClassLoader().loadClass("oracle.jdbc.OracleResultSet"));
	}
	catch (Exception ex) {
		throw new IllegalStateException(
				"Could not initialize OracleJdbc4NativeJdbcExtractor because Oracle API classes are not available: " + ex);
	}
}
 
Example 52
Project: Homework   File: DAOEX01.java   Source Code and License 5 votes vote down vote up
public static  void closeResultSet(ResultSet rs)
{
	if(rs != null)
	{
		try
		{
			rs.close();
		}
		catch(SQLException e)
		{
			LOGGER.catching(e);
		}
	}
}
 
Example 53
Project: Nird2   File: JdbcDatabase.java   Source Code and License 5 votes vote down vote up
@Override
public void updateExpiryTime(Connection txn, ContactId c, MessageId m,
		int maxLatency) throws DbException {
	PreparedStatement ps = null;
	ResultSet rs = null;
	try {
		String sql = "SELECT txCount FROM statuses"
				+ " WHERE messageId = ? AND contactId = ?";
		ps = txn.prepareStatement(sql);
		ps.setBytes(1, m.getBytes());
		ps.setInt(2, c.getInt());
		rs = ps.executeQuery();
		if (!rs.next()) throw new DbStateException();
		int txCount = rs.getInt(1);
		if (rs.next()) throw new DbStateException();
		rs.close();
		ps.close();
		sql = "UPDATE statuses SET expiry = ?, txCount = txCount + 1"
				+ " WHERE messageId = ? AND contactId = ?";
		ps = txn.prepareStatement(sql);
		long now = clock.currentTimeMillis();
		ps.setLong(1, calculateExpiry(now, maxLatency, txCount));
		ps.setBytes(2, m.getBytes());
		ps.setInt(3, c.getInt());
		int affected = ps.executeUpdate();
		if (affected != 1) throw new DbStateException();
		ps.close();
	} catch (SQLException e) {
		tryToClose(rs);
		tryToClose(ps);
		throw new DbException(e);
	}
}
 
Example 54
Project: L2J-Global   File: Post.java   Source Code and License 5 votes vote down vote up
/**
 * @param t
 */
private void load(Topic t)
{
	try (Connection con = DatabaseFactory.getInstance().getConnection();
		PreparedStatement ps = con.prepareStatement("SELECT * FROM posts WHERE post_forum_id=? AND post_topic_id=? ORDER BY post_id ASC"))
	{
		ps.setInt(1, t.getForumID());
		ps.setInt(2, t.getID());
		try (ResultSet rs = ps.executeQuery())
		{
			while (rs.next())
			{
				final CPost cp = new CPost();
				cp.postId = rs.getInt("post_id");
				cp.postOwner = rs.getString("post_owner_name");
				cp.postOwnerId = rs.getInt("post_ownerid");
				cp.postDate = rs.getLong("post_date");
				cp.postTopicId = rs.getInt("post_topic_id");
				cp.postForumId = rs.getInt("post_forum_id");
				cp.postTxt = rs.getString("post_txt");
				_post.add(cp);
			}
		}
	}
	catch (Exception e)
	{
		LOGGER.log(Level.WARNING, "Data error on Post " + t.getForumID() + "/" + t.getID() + " : " + e.getMessage(), e);
	}
}
 
Example 55
Project: lams   File: LoadingCollectionEntry.java   Source Code and License 5 votes vote down vote up
LoadingCollectionEntry(
		ResultSet resultSet,
		CollectionPersister persister,
		Serializable key,
		PersistentCollection collection) {
	this.resultSet = resultSet;
	this.persister = persister;
	this.key = key;
	this.collection = collection;
}
 
Example 56
Project: tcp   File: SqlSelects.java   Source Code and License 5 votes vote down vote up
public static List<ProductoObjetoGasto> selectObjetoGastoCosto(String condicion)throws SQLException{
Connection conect=ConnectionConfiguration.conectarSpr();

String query = " select distinct objeto_gasto from asignacion_presi " + condicion 
				 + " and version = "
                 + " (select max(version) from asignacion_presi " + condicion + ") "
                 + " order by objeto_gasto";

Statement statement = null;
ResultSet rs=null;
List<ProductoObjetoGasto> objetos = new ArrayList<ProductoObjetoGasto>();

try {
	statement = conect.createStatement();
	rs=statement.executeQuery(query);

	while(rs.next()){
		
		ProductoObjetoGasto objeto = new ProductoObjetoGasto();
objeto.setCodigoObjetoGasto(rs.getInt("objeto_gasto"));
objetos.add(objeto);
 	}
	}
	catch (SQLException e) {e.printStackTrace();}
	finally{
	
 	if (statement != null) {statement.close();}
 	if (conect != null) {conect.close();}
	}
	return objetos;
}
 
Example 57
Project: calcite-avatica   File: JdbcMeta.java   Source Code and License 5 votes vote down vote up
public MetaResultSet getVersionColumns(ConnectionHandle ch, String catalog, String schema,
    String table) {
  LOG.trace("getVersionColumns catalog:{} schema:{} table:{}", catalog, schema, table);
  try {
    final ResultSet rs =
        getConnection(ch.id).getMetaData().getVersionColumns(catalog, schema, table);
    int stmtId = registerMetaStatement(rs);
    return JdbcResultSet.create(ch.id, stmtId, rs);
  } catch (SQLException e) {
    throw new RuntimeException(e);
  }
}
 
Example 58
Project: odbaas   File: Database.java   Source Code and License 5 votes vote down vote up
public JSONArray selectAllRow(String query) throws SQLException {
	try {
		Statement st =  connection.createStatement();
		// st.execute("use "+databaseName);
		ResultSet rs = st.executeQuery(query);
		return ResultSetConverter.convert(rs);
	} catch(SQLException e) {
		e.printStackTrace();
		throw e;
	}
}
 
Example 59
Project: parabuild-ci   File: FindFile.java   Source Code and License 5 votes vote down vote up
/**
 * Method declaration
 *
 *
 * @param conn
 * @param name
 *
 * @throws SQLException
 */
static void listFiles(Connection conn, String name) throws SQLException {

    System.out.println("Files like '" + name + "'");

    // Convert to upper case, so the search is case-insensitive
    name = name.toUpperCase();

    // Create a statement object
    Statement stat = conn.createStatement();

    // Now execute the search query
    // UCASE: This is a case insensitive search
    // ESCAPE ':' is used so it can be easily searched for '\'
    ResultSet result = stat.executeQuery("SELECT Path FROM Files WHERE "
                                         + "UCASE(Path) LIKE '%" + name
                                         + "%' ESCAPE ':'");

    // Moves to the next record until no more records
    while (result.next()) {

        // Print the first column of the result
        // could use also getString("Path")
        System.out.println(result.getString(1));
    }

    // Close the ResultSet - not really necessary, but recommended
    result.close();
}
 
Example 60
Project: ChronoBike   File: CSQLPreparedStatement.java   Source Code and License 5 votes vote down vote up
public CSQLResultSet executeQueryCursor(SQL sql)
{
	if(isLogSql())
		Log.logDebug("CSQLPreparedStatement::executeQueryCursor:"+m_csQueryString);
	if(m_PreparedStatement != null)
	{
		try
		{
			sql.startDbIO();
			ResultSet r = m_PreparedStatement.executeQuery();
			if(r != null)
			{
				CSQLResultSet rs = new CSQLResultSet(r, m_semanticContextDef, sql);
				sql.m_sqlStatus.setSQLCode(SQLCode.SQL_OK) ;
				sql.endDbIO();
				return rs ;
			}
			else
			{
				sql.m_sqlStatus.setSQLCode(SQLCode.SQL_NOT_FOUND) ;
				sql.endDbIO();
			}
		}
		catch (SQLException e)
		{
			sql.endDbIO();
			manageSQLException("executeQueryCursor", e, sql);				
		}
	}
	return null;
}