下面列出了java.sql.ResultSet#getBytes ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Returns the block hash for the block stored at the specified height.
*
* @param height
* Chain height
* @return The block hash or null if the block is not found
* @throws BlockStoreException
* Unable to get block from database
*/
@Override
public Sha256Hash getBlockId(int height) throws BlockStoreException {
Sha256Hash blockHash = null;
Connection conn = getConnection();
try (PreparedStatement s = conn.prepareStatement("SELECT block_hash FROM Blocks WHERE block_height=?")) {
s.setInt(1, height);
ResultSet r = s.executeQuery();
if (r.next())
blockHash = new Sha256Hash(r.getBytes(1));
} catch (SQLException exc) {
BTCLoader.error(String.format("Unable to get block hash from database: Height %d", height), exc);
throw new BlockStoreException("Unable to get block hash from database");
}
return blockHash;
}
@Override
public ExecutionMessage mapRow(ResultSet rs, int rowNum) throws SQLException {
return new ExecutionMessage(rs.getLong("EXEC_STATE_ID"),
rs.getString("ASSIGNED_WORKER"),
rs.getString("EXEC_GROUP"),
rs.getString("MSG_ID"),
ExecStatus.find(rs.getInt("STATUS")),
new Payload(rs.getBytes("PAYLOAD")),
rs.getInt("MSG_SEQ_ID"),
rs.getLong("CREATE_TIME"));
}
public ChannelStatusObject (ResultSet set) throws SQLException {
this.pubkeyA = set.getBytes("nodes_a_table.pubkey");
this.pubkeyB = set.getBytes("nodes_b_table.pubkey");
this.infoA = set.getBytes("info_a");
this.infoB = set.getBytes("info_b");
this.signatureA = set.getBytes("signature_a");
this.signatureB = set.getBytes("signature_b");
this.timestamp = set.getInt("timestamp");
}
public StoredHeader getChildHeader(Sha256Hash parentHash) throws BlockStoreException {
StoredHeader header = null;
Connection conn = getConnection();
ResultSet r;
try (PreparedStatement s = conn.prepareStatement("SELECT block_hash,version,timestamp,target_difficulty,"
+ "merkle_root,block_height,chain_work,matches FROM Headers "
+ "WHERE prev_hash_index=? AND prev_hash=?")) {
s.setLong(1, getHashIndex(parentHash));
s.setBytes(2, parentHash.getBytes());
r = s.executeQuery();
if (r.next()) {
Sha256Hash blockHash = new Sha256Hash(r.getBytes(1));
int version = r.getInt(2);
long timestamp = r.getLong(3);
long targetDifficulty = r.getLong(4);
Sha256Hash merkleRoot = new Sha256Hash(r.getBytes(5));
int blockHeight = r.getInt(6);
BigInteger blockWork = new BigInteger(r.getBytes(7));
List<Sha256Hash> matches = getMatches(r.getBytes(8));
header = new StoredHeader(version, blockHash, parentHash, timestamp, targetDifficulty, merkleRoot,
blockHeight >= 0, blockHeight, blockWork, matches);
}
} catch (SQLException exc) {
BTCLoader.error(String.format("Unable to get child header\n Block %s", parentHash), exc);
throw new BlockStoreException("Unable to get child header");
}
return header;
}
/**
* Instantiates a new payment.
*
* @param result the result
* @throws SQLException the SQL exception
*/
public Payment (ResultSet result) throws SQLException {
id = result.getInt("id");
channelIdReceiver = result.getInt("channel_id_receiver");
channelIdSender = result.getInt("channel_id_sender");
amount = result.getLong("amount");
fee = result.getLong("fee");
phaseSender = result.getInt("phase_sender");
phaseReceiver = result.getInt("phase_receiver");
includeInReceiverChannel = Tools.intToBool(result.getInt("include_in_receiver_channel"));
includeInSenderChannel = Tools.intToBool(result.getInt("include_in_sender_channel"));
includeInReceiverChannelTemp = Tools.intToBool(result.getInt("include_in_receiver_channel_temp"));
includeInSenderChannelTemp = Tools.intToBool(result.getInt("include_in_sender_channel_temp"));
secretHash = result.getBytes("secret_hash");
secret = result.getBytes("secret");
timestampAddedReceiver = result.getInt("timestamp_added_receiver");
timestampAddedSender = result.getInt("timestamp_added_sender");
timestampSettledReceiver = result.getInt("timestamp_settled_receiver");
timestampSettledSender = result.getInt("timestamp_settled_sender");
versionAddedReceiver = result.getInt("version_added_receiver");
versionAddedSender = result.getInt("version_added_sender");
versionSettledReceiver = result.getInt("version_settled_receiver");
versionSettledSender = result.getInt("version_settled_sender");
}
@SuppressWarnings("unchecked")
public static List<String> getAsStringListFromBlob(ResultSet resultSet, String columnName)
{
List<String> list;
try
{
byte[] bytes = resultSet.getBytes(columnName);
if (bytes == null || bytes.length < 2) // if json, the column should at least contain "[]"
{
list = new ArrayList<>();
}
else
{
list = new ArrayList<>(
OBJ_MAPPER.readValue(
bytes,
List.class
)
);
}
}
catch (IOException | SQLException exc)
{
throw new LinStorDBRuntimeException(
"Exception occurred while deserializing from json array",
exc
);
}
return list;
}
/**
* Get the value of a column in current row in ResultSet as a string.
*
* For binary data this returns hex-encoded string of the bytes.
*
* For a java object this returns hex-encoded string of the serialized bytes
* for the object.
*/
public static final String getColumnAsString(ResultSet rs, int columnIndex,
int jdbcType) throws SQLException {
byte[] bytes;
switch (jdbcType) {
case Types.BINARY:
case Types.BLOB:
case Types.LONGVARBINARY:
case Types.VARBINARY:
// convert to hex for binary columns
bytes = rs.getBytes(columnIndex);
if (bytes != null) {
return ClientSharedUtils.toHexString(bytes, 0, bytes.length);
}
else {
return null;
}
case Types.JAVA_OBJECT:
// for java object type, serialize and then convert to hex
Object v = rs.getObject(columnIndex);
if (v != null) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
try {
DataSerializer.writeObject(v, dos);
dos.flush();
} catch (IOException ioe) {
// not expected to happen
throw new SQLException(ioe.getMessage(), "XJ001", 0, ioe);
}
bytes = bos.toByteArray();
return ClientSharedUtils.toHexString(bytes, 0, bytes.length);
}
else {
return null;
}
default:
return rs.getString(columnIndex);
}
}
public Object getValidateSource(String id, ResultSet rs) throws SQLException
{
ResultSetMetaData metadata = rs.getMetaData();
byte[] rv = null;
switch(metadata.getColumnType(1))
{
case Types.BLOB:
Blob blob = rs.getBlob(1);
if(blob != null)
{
rv = blob.getBytes(1L, (int) blob.length());
}
else
{
log.info("getValidateSource(" + id + ") blob == null" );
}
break;
case Types.CLOB:
Clob clob = rs.getClob(1);
if(clob != null)
{
rv = clob.getSubString(1L, (int) clob.length()).getBytes();
}
break;
case Types.CHAR:
case Types.LONGVARCHAR:
case Types.VARCHAR:
rv = rs.getString(1).getBytes();
break;
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
rv = rs.getBytes(1);
break;
}
return rv;
}
/**
* Tests that data returned by the last BLOB getter invokation is correct.
*/
public void testCorrectBlobDataWithMultiCall()
throws IOException, SQLException {
setAutoCommit(false);
PreparedStatement psId = prepareStatement("select id from " + TABLE);
String select = "select dBlob from " + TABLE + " where id = ?";
PreparedStatement ps1 = prepareStatement(select);
PreparedStatement ps2 = prepareStatement(select);
ResultSet rsId = psId.executeQuery();
ResultSet rs1;
ResultSet rs2;
while (rsId.next()) {
ps1.setInt(1, rsId.getInt(1));
ps2.setInt(1, rsId.getInt(1));
// getBytes - getString - getBinaryStream
rs1 = ps1.executeQuery();
assertTrue(rs1.next());
rs1.getBytes(1);
rs1.getString(1);
rs2 = ps2.executeQuery();
assertTrue(rs2.next());
assertEquals(rs2.getBinaryStream(1), rs1.getBinaryStream(1));
rs1.close();
rs2.close();
// getString - getBytes - getBlob
rs1 = ps1.executeQuery();
assertTrue(rs1.next());
rs1.getString(1);
rs1.getBytes(1);
rs2 = ps2.executeQuery();
assertTrue(rs2.next());
assertEquals(rs2.getBlob(1), rs1.getBlob(1));
rs1.close();
rs2.close();
// getBytes - getString - getCharacterStream
rs1 = ps1.executeQuery();
assertTrue(rs1.next());
rs1.getBytes(1);
rs1.getString(1);
rs2 = ps2.executeQuery();
assertTrue(rs2.next());
assertEquals(rs2.getCharacterStream(1), rs1.getCharacterStream(1));
rs1.close();
rs2.close();
// getBytes - getString - getBytes
rs1 = ps1.executeQuery();
assertTrue(rs1.next());
rs1.getBytes(1);
rs1.getString(1);
rs2 = ps2.executeQuery();
assertTrue(rs2.next());
assertTrue(Arrays.equals(rs2.getBytes(1), rs1.getBytes(1)));
rs1.close();
rs2.close();
// getBytes - getString - getString
rs1 = ps1.executeQuery();
assertTrue(rs1.next());
rs1.getBytes(1);
rs1.getString(1);
rs2 = ps2.executeQuery();
assertTrue(rs2.next());
assertEquals(rs2.getString(1), rs1.getString(1));
rs1.close();
rs2.close();
// getString - getBytes - getObject
rs1 = ps1.executeQuery();
assertTrue(rs1.next());
rs1.getString(1);
rs1.getBytes(1);
rs2 = ps2.executeQuery();
assertTrue(rs2.next());
Blob b1 = (Blob)rs1.getObject(1);
Blob b2 = (Blob)rs2.getObject(1);
assertEquals(b2, b1);
rs1.close();
rs2.close();
// getBytes - getString - getAsciiStream
rs1 = ps1.executeQuery();
assertTrue(rs1.next());
rs1.getBytes(1);
rs1.getString(1);
rs2 = ps2.executeQuery();
assertTrue(rs2.next());
assertEquals(rs2.getAsciiStream(1), rs1.getAsciiStream(1));
rs1.close();
rs2.close();
}
rollback();
}
@Override
public byte[] getNullableResult(ResultSet rs, int columnIndex)
throws SQLException {
return rs.getBytes(columnIndex);
}
@Override
public PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementDAOException {
PreparedStatement stmt = null;
ResultSet resultSet = null;
CertificateResponse certificateResponse;
List<CertificateResponse> certificates = new ArrayList<>();
PaginationResult paginationResult;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
Connection conn = this.getConnection();
String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME FROM "
+ "DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC LIMIT ?,?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
stmt.setInt(2, rowNum);
stmt.setInt(3, limit);
resultSet = stmt.executeQuery();
int resultCount = 0;
while (resultSet.next()) {
certificateResponse = new CertificateResponse();
byte[] certificateBytes = resultSet.getBytes("CERTIFICATE");
certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER"));
certificateResponse.setTenantId(resultSet.getInt("TENANT_ID"));
certificateResponse.setUsername(resultSet.getString("USERNAME"));
CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse);
certificates.add(certificateResponse);
resultCount++;
}
paginationResult = new PaginationResult();
paginationResult.setData(certificates);
paginationResult.setRecordsTotal(resultCount);
} catch (SQLException e) {
String errorMsg = "SQL error occurred while retrieving the certificates.";
log.error(errorMsg, e);
throw new CertificateManagementDAOException(errorMsg, e);
} finally {
CertificateManagementDAOUtil.cleanupResources(stmt, resultSet);
}
return paginationResult;
}
static void get_using_bytes(ResultSet rs, int col_no) throws Exception{
System.out.println("getBytes(" + col_no + ")");
byte[] bytearray = (byte[]) rs.getBytes(col_no);
printbytearray(bytearray, bytearray.length, 0);
System.out.println("");
}
/**
* {@inheritDoc}
*/
public synchronized List<NodeId> getAllNodeIds(NodeId bigger, int maxCount)
throws ItemStateException, RepositoryException {
ResultSet rs = null;
try {
String sql = bundleSelectAllIdsSQL;
NodeId lowId = null;
Object[] keys = new Object[0];
if (bigger != null) {
sql = bundleSelectAllIdsFromSQL;
lowId = bigger;
keys = getKey(bigger);
}
if (getStorageModel() == SM_LONGLONG_KEYS && maxCount > 0) {
// get some more rows, in case the first row is smaller
// only required for SM_LONGLONG_KEYS
// probability is very low to get get the wrong first key, < 1 : 2^64
// see also bundleSelectAllIdsFrom SQL statement
maxCount += 10;
}
rs = conHelper.exec(sql, keys, false, maxCount);
ArrayList<NodeId> result = new ArrayList<NodeId>();
while ((maxCount == 0 || result.size() < maxCount) && rs.next()) {
NodeId current;
if (getStorageModel() == SM_BINARY_KEYS) {
current = new NodeId(rs.getBytes(1));
} else {
long high = rs.getLong(1);
long low = rs.getLong(2);
current = new NodeId(high, low);
if (lowId != null) {
// skip the keys that are smaller or equal (see above, maxCount += 10)
// only required for SM_LONGLONG_KEYS
if (current.compareTo(lowId) <= 0) {
continue;
}
}
}
result.add(current);
}
return result;
} catch (SQLException e) {
String msg = "getAllNodeIds failed.";
log.error(msg, e);
throw new ItemStateException(msg, e);
} finally {
DbUtility.close(rs);
}
}
@Override
public JobStatus getJobStatusFromExecution(final long executionId) {
Connection conn = null;
PreparedStatement statement = null;
ResultSet rs = null;
try {
conn = getConnection();
statement = conn.prepareStatement(dictionary.getFindJobStatus());
statement.setLong(1, executionId);
rs = statement.executeQuery();
if (rs.next()) {
final long jobInstanceId = rs.getLong(dictionary.jobExecutionColumns(8));
final String batchStatus = rs.getString(dictionary.jobExecutionColumns(1));
final byte[] jobXmls = rs.getBytes(dictionary.jobInstanceColumns(4));
final JobInstanceImpl jobInstance;
if (jobXmls != null) {
jobInstance = new JobInstanceImpl(jobInstanceId, new String(jobXmls, UTF_8));
} else {
jobInstance = new JobInstanceImpl(jobInstanceId);
}
jobInstance.setJobName(rs.getString(dictionary.jobInstanceColumns(3)));
final JobStatus status = new JobStatus(jobInstanceId);
status.setExitStatus(rs.getString(dictionary.jobInstanceColumns(2)));
status.setLatestExecutionId(rs.getLong(dictionary.jobInstanceColumns(5)));
status.setRestartOn(rs.getString(dictionary.jobInstanceColumns(6)));
status.setCurrentStepId(rs.getString(dictionary.jobInstanceColumns(7)));
status.setJobInstance(jobInstance);
if (batchStatus != null) {
status.setBatchStatus(BatchStatus.valueOf(batchStatus));
}
return status;
}
return null;
} catch (final Exception e) {
throw new PersistenceException(e);
} finally {
cleanupConnection(conn, rs, statement);
}
}
public Avatar mapRow(ResultSet rs, int rowNum) throws SQLException {
return new Avatar(rs.getInt(1), rs.getString(2), rs.getTimestamp(3), rs.getString(4),
rs.getInt(5), rs.getInt(6), rs.getBytes(7));
}
@Override
public byte[] handleColumn(ResultSet resultSet, int column) throws SQLException {
return resultSet.getBytes(column);
}
public RevocationHash (ResultSet set) throws SQLException {
this.secretHash = set.getBytes("secretHash");
this.secret = set.getBytes("secret");
this.depth = set.getInt("depth");
this.child = set.getInt("child");
}
protected Object getValueFromResultSetDo(ResultSet result) throws SQLException {
return result.getBytes(getColumnName());
}
/**
* 从oracle的resultset中得到value
*
* <pre>
* 1. 对于DATE类型特殊处理成TIMESTAMP类型,否则复制过去会丢掉时间部分
* 2. 如果为字符串类型,并且需要进行转码,那么进行编码转换。
* </pre>
*/
public ColumnValue getColumnValue(ResultSet rs, String encoding, ColumnMeta col) throws SQLException {
Object value = null;
if (col.getType() == Types.DATE) {
value = rs.getTimestamp(col.getName());
col = new ColumnMeta(col.getName(), Types.TIMESTAMP);
} else if (col.getType() == Types.TIMESTAMP) {
value = rs.getTimestamp(col.getName());
col = new ColumnMeta(col.getName(), Types.TIMESTAMP);
} else if (YuGongUtils.isCharType(col.getType())) {
// byte[] bytes = rs.getBytes(col.getName());
// if (bytes == null) {
// value = rs.getObject(col.getName());
// } else {
// try {
// value = new String(bytes, encoding);
// } catch (UnsupportedEncodingException e) {
// throw new YuGongException("codec error!!", e);
// }
// }
value = rs.getString(col.getName());
} else if (YuGongUtils.isClobType(col.getType())) {
// Clob c = rs.getClob(col.getName());
// if (c == null) {
// value = rs.getObject(col.getName());
// } else {
// InputStream is = c.getAsciiStream();
// byte[] bb = new byte[(int) c.length()];
// try {
// is.read(bb);
// } catch (IOException e) {
// throw new SQLException("read from clob error,column:" +
// col.getName(), e);
// }
//
// try {
// value = new String(bb, encoding);
// } catch (UnsupportedEncodingException e) {
// throw new RuntimeException("codec error!!", e);
// }
// }
value = rs.getString(col.getName());
} else if (YuGongUtils.isBlobType(col.getType())) {
value = rs.getBytes(col.getName());
} else {
value = rs.getObject(col.getName());
}
// 使用clone对象,避免translator修改了引用
return new ColumnValue(col.clone(), value);
}
@Override
public Byte[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
byte[] bytes = rs.getBytes(columnIndex);
return getBytes(bytes);
}