Java Code Examples for java.sql.ResultSet.getBytes()

The following are Jave code examples for showing how to use getBytes() of the java.sql.ResultSet class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Nird2   File: JdbcDatabase.java   View Source Code Vote up 6 votes
@Override
@Nullable
public byte[] getRawMessage(Connection txn, MessageId m)
		throws DbException {
	PreparedStatement ps = null;
	ResultSet rs = null;
	try {
		String sql = "SELECT raw FROM messages WHERE messageId = ?";
		ps = txn.prepareStatement(sql);
		ps.setBytes(1, m.getBytes());
		rs = ps.executeQuery();
		if (!rs.next()) throw new DbStateException();
		byte[] raw = rs.getBytes(1);
		if (rs.next()) throw new DbStateException();
		rs.close();
		ps.close();
		return raw;
	} catch (SQLException e) {
		tryToClose(rs);
		tryToClose(ps);
		throw new DbException(e);
	}
}
 
Example 2
Project: IDBuilderFX   File: ViewSingleParsedController.java   View Source Code Vote up 6 votes
public void viewSingle() throws SQLException, IOException {
	Connection c;
	c = database.SqliteConnection.getConnection();
	String SQL = "SELECT * from Employee";
	ResultSet rs = c.createStatement().executeQuery(SQL);
	while (rs.next()) {
		namelbl.setText(rs.getString(2));
		emaillbl.setText(rs.getString(3));
		moblbl.setText(rs.getString(4));
		addlbl.setText(rs.getString(5));
		addlbl.setWrapText(true);
		doblbl.setText(rs.getString(6));
		sexlbl.setText(rs.getString(7));
		fnamelbl.setText(rs.getString(8));
		byte[] imageInbyte = rs.getBytes(9);
		BufferedImage img1 = ImageIO.read(new ByteArrayInputStream(imageInbyte));
		Image image = SwingFXUtils.toFXImage(img1, null);
		photo.setImage(image);
		photo.setPreserveRatio(true);
	}
	c.close();
}
 
Example 3
Project: Nird2   File: JdbcDatabase.java   View Source Code Vote up 6 votes
@Override
public Collection<Group> getGroups(Connection txn, ClientId c)
		throws DbException {
	PreparedStatement ps = null;
	ResultSet rs = null;
	try {
		String sql = "SELECT groupId, descriptor FROM groups"
				+ " WHERE clientId = ?";
		ps = txn.prepareStatement(sql);
		ps.setString(1, c.getString());
		rs = ps.executeQuery();
		List<Group> groups = new ArrayList<Group>();
		while (rs.next()) {
			GroupId id = new GroupId(rs.getBytes(1));
			byte[] descriptor = rs.getBytes(2);
			groups.add(new Group(id, c, descriptor));
		}
		rs.close();
		ps.close();
		return groups;
	} catch (SQLException e) {
		tryToClose(rs);
		tryToClose(ps);
		throw new DbException(e);
	}
}
 
Example 4
Project: eXperDB-DB2PG   File: DatabaseUtil.java   View Source Code Vote up 6 votes
public static Object PreparedStmtSetValue(int columnType, ResultSet rs, int index) throws SQLException, IOException{
	StringBuffer sb = new StringBuffer();
	switch(columnType){
	case 2005:  //CLOB
		Clob clob = rs.getClob(index);
		
		if (clob == null){
			return null;
		}
		
		Reader reader = clob.getCharacterStream();
		char[] buffer = new char[(int)clob.length()];
		while(reader.read(buffer) != -1){
			sb.append(buffer);				
		}
		return sb.toString();
	case 2004:  //BLOB			
		Blob blob = rs.getBlob(index);
		
		if (blob == null){
			return null;
		}
		
		InputStream in = blob.getBinaryStream();
		byte[] Bytebuffer = new byte[(int)blob.length()];
		in.read(Bytebuffer);
		return Bytebuffer;
	case -2:
		return rs.getBytes(index);
	default:
		return rs.getObject(index);
	}	
}
 
Example 5
Project: JPA-Demo   File: SQLDelete.java   View Source Code Vote up 6 votes
private static void printEmployees() throws SQLException {
	Statement stmt = c.createStatement();
	String sql = "SELECT * FROM employees";
	ResultSet rs = stmt.executeQuery(sql);
	while (rs.next()) {
		int id = rs.getInt("id");
		String name = rs.getString("name");
		Date dob = rs.getDate("dob");
		String address = rs.getString("address");
		Double salary = rs.getDouble("salary");
		byte[] photo = rs.getBytes("photo");
		Department dep = getDepartments(rs.getInt("dep_id"));
		Employee employee = new Employee(id, name, dob, address, salary, photo, dep);
		System.out.println(employee);
	}
	rs.close();
	stmt.close();
}
 
Example 6
Project: BibliotecaPS   File: BlobRegressionTest.java   View Source Code Vote up 5 votes
/**
 * @throws Exception
 */
public void testUpdatableBlobsWithCharsets() throws Exception {
    byte[] smallBlob = new byte[32];

    for (byte i = 0; i < smallBlob.length; i++) {
        smallBlob[i] = i;
    }

    createTable("testUpdatableBlobsWithCharsets", "(pk INT NOT NULL PRIMARY KEY, field1 BLOB)");
    this.pstmt = this.conn.prepareStatement("INSERT INTO testUpdatableBlobsWithCharsets (pk, field1) VALUES (1, ?)");
    this.pstmt.setBinaryStream(1, new ByteArrayInputStream(smallBlob), smallBlob.length);
    this.pstmt.executeUpdate();

    Statement updStmt = this.conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

    this.rs = updStmt.executeQuery("SELECT pk, field1 FROM testUpdatableBlobsWithCharsets");
    System.out.println(this.rs);
    this.rs.next();

    for (byte i = 0; i < smallBlob.length; i++) {
        smallBlob[i] = (byte) (i + 32);
    }

    this.rs.updateBinaryStream(2, new ByteArrayInputStream(smallBlob), smallBlob.length);
    this.rs.updateRow();

    ResultSet newRs = this.stmt.executeQuery("SELECT field1 FROM testUpdatableBlobsWithCharsets");

    newRs.next();

    byte[] updatedBlob = newRs.getBytes(1);

    for (byte i = 0; i < smallBlob.length; i++) {
        byte origValue = smallBlob[i];
        byte newValue = updatedBlob[i];

        assertTrue("Original byte at position " + i + ", " + origValue + " != new value, " + newValue, origValue == newValue);
    }

}
 
Example 7
Project: Nird2   File: JdbcDatabase.java   View Source Code Vote up 5 votes
@Override
public Map<MessageId, State> getMessageDependencies(Connection txn,
		MessageId m) throws DbException {
	PreparedStatement ps = null;
	ResultSet rs = null;
	try {
		String sql = "SELECT d.dependencyId, m.state, d.groupId, m.groupId"
				+ " FROM messageDependencies AS d"
				+ " LEFT OUTER JOIN messages AS m"
				+ " ON d.dependencyId = m.messageId"
				+ " WHERE d.messageId = ?";
		ps = txn.prepareStatement(sql);
		ps.setBytes(1, m.getBytes());
		rs = ps.executeQuery();
		Map<MessageId, State> dependencies = new HashMap<MessageId, State>();
		while (rs.next()) {
			MessageId dependency = new MessageId(rs.getBytes(1));
			State state = State.fromValue(rs.getInt(2));
			if (rs.wasNull()) {
				state = UNKNOWN; // Missing dependency
			} else {
				GroupId dependentGroupId = new GroupId(rs.getBytes(3));
				GroupId dependencyGroupId = new GroupId(rs.getBytes(4));
				if (!dependentGroupId.equals(dependencyGroupId))
					state = INVALID; // Dependency in another group
			}
			dependencies.put(dependency, state);
		}
		rs.close();
		ps.close();
		return dependencies;
	} catch (SQLException e) {
		tryToClose(rs);
		tryToClose(ps);
		throw new DbException(e);
	}
}
 
Example 8
Project: burstcoin   File: AT.java   View Source Code Vote up 5 votes
private ATState(ResultSet rs) throws SQLException {
	this.atId = rs.getLong("at_id");
	this.dbKey = atStateDbKeyFactory.newKey(this.atId);
	this.state = rs.getBytes("state");
	this.prevHeight = rs.getInt("prev_height");
	this.nextHeight = rs.getInt("next_height");
	this.sleepBetween = rs.getInt("sleep_between");
	this.prevBalance = rs.getLong("prev_balance");
	this.freezeWhenSameBalance = rs.getBoolean("freeze_when_same_balance");
	this.minActivationAmount = rs.getLong("min_activate_amount");
}
 
Example 9
Project: Nird2   File: JdbcDatabase.java   View Source Code Vote up 5 votes
@Override
public LocalAuthor getLocalAuthor(Connection txn, AuthorId a)
		throws DbException {
	PreparedStatement ps = null;
	ResultSet rs = null;
	try {
		String sql = "SELECT name, publicKey, privateKey, created"
				+ " FROM localAuthors"
				+ " WHERE authorId = ?";
		ps = txn.prepareStatement(sql);
		ps.setBytes(1, a.getBytes());
		rs = ps.executeQuery();
		if (!rs.next()) throw new DbStateException();
		String name = rs.getString(1);
		byte[] publicKey = rs.getBytes(2);
		byte[] privateKey = rs.getBytes(3);
		long created = rs.getLong(4);
		LocalAuthor localAuthor = new LocalAuthor(a, name, publicKey,
				privateKey, created);
		if (rs.next()) throw new DbStateException();
		rs.close();
		ps.close();
		return localAuthor;
	} catch (SQLException e) {
		tryToClose(rs);
		tryToClose(ps);
		throw new DbException(e);
	}
}
 
Example 10
Project: burstcoin   File: Account.java   View Source Code Vote up 5 votes
private Account(ResultSet rs) throws SQLException {
    this.id = rs.getLong("id");
    this.dbKey = accountDbKeyFactory.newKey(this.id);
    this.creationHeight = rs.getInt("creation_height");
    this.publicKey = rs.getBytes("public_key");
    this.keyHeight = rs.getInt("key_height");
    this.balanceNQT = rs.getLong("balance");
    this.unconfirmedBalanceNQT = rs.getLong("unconfirmed_balance");
    this.forgedBalanceNQT = rs.getLong("forged_balance");
    this.name = rs.getString("name");
    this.description = rs.getString("description");
}
 
Example 11
Project: letv   File: Database.java   View Source Code Vote up 5 votes
public String getString(int n) {
    try {
        ResultSet rs = getResultSet();
        if (rs == null) {
            return "";
        }
        return new String(rs.getBytes(n));
    } catch (Exception e) {
        Debug.warning(e);
        return "";
    }
}
 
Example 12
Project: lams   File: DefaultLobHandler.java   View Source Code Vote up 5 votes
@Override
public byte[] getBlobAsBytes(ResultSet rs, int columnIndex) throws SQLException {
	logger.debug("Returning BLOB as bytes");
	if (this.wrapAsLob) {
		Blob blob = rs.getBlob(columnIndex);
		return blob.getBytes(1, (int) blob.length());
	}
	else {
		return rs.getBytes(columnIndex);
	}
}
 
Example 13
Project: Nird2   File: JdbcDatabase.java   View Source Code Vote up 5 votes
@Override
public LocalAuthor getLocalAuthor(Connection txn, AuthorId a)
		throws DbException {
	PreparedStatement ps = null;
	ResultSet rs = null;
	try {
		String sql = "SELECT name, publicKey, privateKey, created"
				+ " FROM localAuthors"
				+ " WHERE authorId = ?";
		ps = txn.prepareStatement(sql);
		ps.setBytes(1, a.getBytes());
		rs = ps.executeQuery();
		if (!rs.next()) throw new DbStateException();
		String name = rs.getString(1);
		byte[] publicKey = rs.getBytes(2);
		byte[] privateKey = rs.getBytes(3);
		long created = rs.getLong(4);
		LocalAuthor localAuthor = new LocalAuthor(a, name, publicKey,
				privateKey, created);
		if (rs.next()) throw new DbStateException();
		rs.close();
		ps.close();
		return localAuthor;
	} catch (SQLException e) {
		tryToClose(rs);
		tryToClose(ps);
		throw new DbException(e);
	}
}
 
Example 14
Project: parabuild-ci   File: TestSelf.java   View Source Code Vote up 5 votes
static void readTabProfileTest(Statement sStatement) throws Exception {

        String    s = "select * from TabProfile where id=-2";
        ResultSet r = sStatement.executeQuery(s);

        r.next();

        if (!r.getString(2).equals("\"Birdie\"'s car ?")) {
            throw new Exception("Unicode error.");
        }

        boolean mismatch = false;
        byte[]  b2n      = r.getBytes(4);

        for (int i = 0; i < b2n.length; i++) {
            if (b2[i] != b2n[i]) {
                mismatch = true;
            }
        }

        r.close();

        s = "select * from TabProfile where id=10";
        r = sStatement.executeQuery(s);

        r.next();

        byte[] b1n = r.getBytes(4);

        for (int i = 0; i < b1n.length; i++) {
            if (b1[i] != b1n[i]) {
                mismatch = true;
            }
        }

        r.close();
    }
 
Example 15
Project: Nird2   File: JdbcDatabase.java   View Source Code Vote up 5 votes
@Override
public Map<MessageId, State> getMessageDependencies(Connection txn,
		MessageId m) throws DbException {
	PreparedStatement ps = null;
	ResultSet rs = null;
	try {
		String sql = "SELECT d.dependencyId, m.state, d.groupId, m.groupId"
				+ " FROM messageDependencies AS d"
				+ " LEFT OUTER JOIN messages AS m"
				+ " ON d.dependencyId = m.messageId"
				+ " WHERE d.messageId = ?";
		ps = txn.prepareStatement(sql);
		ps.setBytes(1, m.getBytes());
		rs = ps.executeQuery();
		Map<MessageId, State> dependencies = new HashMap<MessageId, State>();
		while (rs.next()) {
			MessageId dependency = new MessageId(rs.getBytes(1));
			State state = State.fromValue(rs.getInt(2));
			if (rs.wasNull()) {
				state = UNKNOWN; // Missing dependency
			} else {
				GroupId dependentGroupId = new GroupId(rs.getBytes(3));
				GroupId dependencyGroupId = new GroupId(rs.getBytes(4));
				if (!dependentGroupId.equals(dependencyGroupId))
					state = INVALID; // Dependency in another group
			}
			dependencies.put(dependency, state);
		}
		rs.close();
		ps.close();
		return dependencies;
	} catch (SQLException e) {
		tryToClose(rs);
		tryToClose(ps);
		throw new DbException(e);
	}
}
 
Example 16
Project: pugtsdb   File: RollUpGranularitySteps.java   View Source Code Vote up 5 votes
@And("^a point on \"([^\"]*)\" \"([^\"]*)\" will be rolled up by (\\d+) \"([^\"]*)\" with a double (\\d+)$")
public void aPointOnWillBeRolledUpByWithADouble(String timestampState,
                                                String timestampUnit,
                                                long granularityValue,
                                                String granularityUnit,
                                                Double expectedValue) throws Throwable {
    String sql = ""
            + " SELECT \"value\"          "
            + " FROM   point_" + granularityOf(granularityValue, granularityUnit)
            + " WHERE  \"metric_id\" = ?   "
            + " AND    \"timestamp\" = ?   "
            + " AND    \"aggregation\" = ? ";

    Timestamp timestamp = resolveTimestamp(timestampState, timestampUnit);

    try (Connection connection = pugTSDB.getDataSource().getConnection();
         PreparedStatement statement = connection.prepareStatement(sql)) {
        statement.setInt(1, metric.getId());
        statement.setTimestamp(2, timestamp);
        statement.setString(3, aggregation.getName());
        ResultSet resultSet = statement.executeQuery();

        assertTrue(resultSet.next());

        byte[] actualBytes = resultSet.getBytes(1);
        Object actualValue = metric.valueFromBytes(actualBytes);

        if (expectedValue == null) {
            assertNull(actualValue);
        } else {
            assertEquals(expectedValue, actualValue);
        }
    }
}
 
Example 17
Project: ProyectoPacientes   File: BlobRegressionTest.java   View Source Code Vote up 5 votes
/**
 * @throws Exception
 */
public void testUpdatableBlobsWithCharsets() throws Exception {
    byte[] smallBlob = new byte[32];

    for (byte i = 0; i < smallBlob.length; i++) {
        smallBlob[i] = i;
    }

    createTable("testUpdatableBlobsWithCharsets", "(pk INT NOT NULL PRIMARY KEY, field1 BLOB)");
    this.pstmt = this.conn.prepareStatement("INSERT INTO testUpdatableBlobsWithCharsets (pk, field1) VALUES (1, ?)");
    this.pstmt.setBinaryStream(1, new ByteArrayInputStream(smallBlob), smallBlob.length);
    this.pstmt.executeUpdate();

    Statement updStmt = this.conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

    this.rs = updStmt.executeQuery("SELECT pk, field1 FROM testUpdatableBlobsWithCharsets");
    System.out.println(this.rs);
    this.rs.next();

    for (byte i = 0; i < smallBlob.length; i++) {
        smallBlob[i] = (byte) (i + 32);
    }

    this.rs.updateBinaryStream(2, new ByteArrayInputStream(smallBlob), smallBlob.length);
    this.rs.updateRow();

    ResultSet newRs = this.stmt.executeQuery("SELECT field1 FROM testUpdatableBlobsWithCharsets");

    newRs.next();

    byte[] updatedBlob = newRs.getBytes(1);

    for (byte i = 0; i < smallBlob.length; i++) {
        byte origValue = smallBlob[i];
        byte newValue = updatedBlob[i];

        assertTrue("Original byte at position " + i + ", " + origValue + " != new value, " + newValue, origValue == newValue);
    }

}
 
Example 18
Project: message-broker   File: MessageDaoImpl.java   View Source Code Vote up 4 votes
@SuppressFBWarnings("SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING")
private void populateMessageWithMetadata(Connection connection,
                                         String idListAsString, List<Long> idList,
                                         Map<Long, Message> messageMap) throws SQLException, BrokerException {
    String metadataSql = "SELECT MESSAGE_ID, EXCHANGE_NAME, ROUTING_KEY, CONTENT_LENGTH, MESSAGE_METADATA "
            + " FROM MB_METADATA WHERE MESSAGE_ID IN (" + idListAsString + ") ORDER BY MESSAGE_ID";


    PreparedStatement selectMetadata = null;
    ResultSet metadataResultSet = null;

    try {
        selectMetadata = connection.prepareStatement(metadataSql);
        for (int i = 0; i < idList.size(); i++) {
            selectMetadata.setLong(i + 1, idList.get(i));
        }

        metadataResultSet = selectMetadata.executeQuery();
        while (metadataResultSet.next()) {
            long messageId = metadataResultSet.getLong(1);
            String exchangeName = metadataResultSet.getString(2);
            String routingKey = metadataResultSet.getString(3);
            long contentLength = metadataResultSet.getLong(4);
            byte[] bytes = metadataResultSet.getBytes(5);
            ByteBuf buffer = Unpooled.wrappedBuffer(bytes);
            try {
                Metadata metadata = new Metadata(messageId, routingKey, exchangeName, contentLength);
                metadata.setProperties(FieldTable.parse(buffer));
                metadata.setHeaders(FieldTable.parse(buffer));
                Message message = new Message(metadata);
                messageMap.put(messageId, message);
            } catch (Exception e) {
                throw new BrokerException("Error occurred while parsing metadata properties", e);
            } finally {
                buffer.release();
            }
        }
    } finally {
        close(metadataResultSet);
        close(selectMetadata);
    }
}
 
Example 19
Project: OpenDiabetes   File: TestLobs.java   View Source Code Vote up 4 votes
public void testBlobI() {

        System.out.println("Starting (sub-)test: " + getName());

        try {
            Statement st = connection.createStatement();

            st.executeUpdate("drop table BLOBTEST if exists");
            st.executeUpdate("create table BLOBTEST (BT_BLOB BLOB)");
            System.out.println("Running insert...");

            PreparedStatement insert =
                connection.prepareStatement("insert into BLOBTEST values(?)");

            insert.setBytes(1, new byte[]{});
            insert.executeUpdate();
            System.out.println("Running update...");

            PreparedStatement update = connection.prepareStatement(
                "update BLOBTEST set BT_BLOB = CONCAT(BT_BLOB,?)");

            update.setBytes(1, new byte[] {
                1, 2, 3
            });
            update.executeUpdate();
            System.out.println("Running select...");

            PreparedStatement select =
                connection.prepareStatement("select BT_BLOB from BLOBTEST");
            ResultSet result = select.executeQuery();

            System.out.println("Results: " + result.getFetchSize());

            while (result.next()) {
                byte[] data = result.getBytes(1);
                String s = data == null ? "null"
                                        : String.valueOf(data.length);
                System.out.println("Result: " + s);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            fail("test failure");
        }
    }
 
Example 20
Project: dev-courses   File: TestLobs.java   View Source Code Vote up 4 votes
public void testBlobI() {

        System.out.println("Starting (sub-)test: " + getName());

        try {
            Statement st = connection.createStatement();

            st.executeUpdate("drop table BLOBTEST if exists");
            st.executeUpdate("create table BLOBTEST (BT_BLOB BLOB)");
            System.out.println("Running insert...");

            PreparedStatement insert =
                connection.prepareStatement("insert into BLOBTEST values(?)");

            insert.setBytes(1, new byte[]{});
            insert.executeUpdate();
            System.out.println("Running update...");

            PreparedStatement update = connection.prepareStatement(
                "update BLOBTEST set BT_BLOB = CONCAT(BT_BLOB,?)");

            update.setBytes(1, new byte[] {
                1, 2, 3
            });
            update.executeUpdate();
            System.out.println("Running select...");

            PreparedStatement select =
                connection.prepareStatement("select BT_BLOB from BLOBTEST");
            ResultSet result = select.executeQuery();

            System.out.println("Results: " + result.getFetchSize());

            while (result.next()) {
                byte[] data = result.getBytes(1);
                String s = data == null ? "null"
                                        : String.valueOf(data.length);
                System.out.println("Result: " + s);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            fail("test failure");
        }
    }