private void testUnsupportedOperations() throws Exception { Connection conn = getConnection(); stat = conn.createStatement(); stat.execute("create table test(id int, c clob, b blob)"); stat.execute("insert into test values(1, 'x', x'00')"); ResultSet rs = stat.executeQuery("select * from test order by id"); rs.next(); Clob clob = rs.getClob(2); byte[] data = IOUtils.readBytesAndClose(clob.getAsciiStream(), -1); assertEquals("x", new String(data, "UTF-8")); assertTrue(clob.toString().endsWith("'x'")); clob.free(); assertTrue(clob.toString().endsWith("null")); assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, clob).truncate(0); assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, clob).setAsciiStream(1); assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, clob).setString(1, "", 0, 1); assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, clob).position("", 0); assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, clob).position((Clob) null, 0); assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, clob).getCharacterStream(1, 1); Blob blob = rs.getBlob(3); assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, blob).truncate(0); assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, blob).setBytes(1, new byte[0], 0, 0); assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, blob).position(new byte[1], 0); assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, blob).position((Blob) null, 0); assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, blob).getBinaryStream(1, 1); assertTrue(blob.toString().endsWith("X'00'")); blob.free(); assertTrue(blob.toString().endsWith("null")); stat.execute("drop table test"); conn.close(); }
static void read() throws SQLException, IOException { Connection conn = null; Statement st = null; ResultSet rs = null; try { conn = JdbcUtils.getConnection(); // conn = JdbcUtilsSingle.getInstance().getConnection(); st = conn.createStatement(); rs = st.executeQuery("select text from textdemo"); while (rs.next()) { Blob blob = rs.getBlob(1); InputStream in = blob.getBinaryStream(); // reader = rs.getCharacterStream(1); File file = new File("JdbcUtils_bak.java"); OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); byte[] buff = new byte[1024]; for (int i = 0; (i = in.read(buff)) > 0; ) { out.write(buff, 0, i); } out.close(); in.close(); } } finally { JdbcUtils.free(rs, st, conn); } }
@Override public Article mapRow(ResultSet rs, int rowNum) throws SQLException { Article a = new Article(); a.setId(rs.getInt("id")); a.setTitle(rs.getString("title")); Blob blob = rs.getBlob("content"); int len = (int) blob.length(); byte[] data = blob.getBytes(0, len); String content = new String(data); a.setContent(content); a.setCtime(rs.getTimestamp("ctime")); a.setUptime(rs.getTimestamp("uptime")); a.setTags(rs.getString("tags")); a.setCategory(rs.getString("category")); a.setAuthorId(rs.getInt("authorId")); a.setEditorId(rs.getInt("editorId")); a.setMediaId(rs.getInt("mediaId")); a.setPics(rs.getString("pics")); a.setExtra(rs.getString("extra")); return a; }
@Override public Object fetchBLOB(ResultSet rs, int column, EOAttribute attribute, boolean materialize) throws SQLException { NSData data = null; Blob blob = rs.getBlob(column); if (blob == null) { return null; } if (!materialize) { return blob; } InputStream stream = blob.getBinaryStream(); try { int chunkSize = (int) blob.length(); if (chunkSize == 0) { data = NSData.EmptyData; } else { data = new NSData(stream, chunkSize); } } catch (IOException e) { throw new JDBCAdaptorException(e.getMessage(), null); } finally { try { if (stream != null) stream.close(); } catch (IOException e) { /* Nothing we can do */ } ; } return data; }
public String getValue(int idx) { String val = ""; try { int cType = getColumnType(idx); if (cType == 2004) { // BLOB val = "BLOB"; Blob blob = rs.getBlob(idx); if (blob == null) { val = null; } else { val = "BLOB size=" + blob.length(); } } else val = rs.getString(idx); } catch (SQLException e) { val = e.getMessage(); int cType = getColumnType(idx); System.err.print("Column type: " + cType); } if (val != null && val.endsWith(" 00:00:00.0")) val = val.substring(0, val.length() - 11); return val; }
public void testUpdateExisting() throws Exception { Content content = addContent(); byte[] bytes = new byte[1024]; Blob data = new OutputBlob(new ByteArrayInputStream(bytes), bytes.length); Content newContent = new Content( content.getContentId(), nextLong(), randomString(), nextLong(), nextLong(), randomString(), randomString(), data, data.length()); _persistence.update(newContent); Content existingContent = _persistence.findByPrimaryKey(newContent.getContentId()); assertTrue(existingContent.equals(newContent)); }
public String getBlob(int idx) { String val = ""; try { int cType = getColumnType(idx); if (cType == 2004) { // BLOB val = "BLOB"; Blob blob = rs.getBlob(idx); if (blob == null) { val = null; } else { byte[] bdata = blob.getBytes(1, (int) blob.length()); val = new String(bdata); } } else val = rs.getString(idx); } catch (SQLException e) { val = e.getMessage(); int cType = getColumnType(idx); System.err.print("Column type: " + cType); } // if (val != null && val.endsWith(" 00:00:00.0")) val = val.substring(0, val.length()-11); // System.out.print("BLOB=" + val); return val; }
@SuppressWarnings("unchecked") @Override public final T deserialize(Object value) { InputStream is = null; if (value instanceof Blob) { Blob blob = (Blob) value; try { is = blob.getBinaryStream(); } catch (SQLException e) { throw new IciqlException(e); } } else if (value instanceof byte[]) { byte[] bytes = (byte[]) value; is = new ByteArrayInputStream(bytes); } try { T object = (T) new ObjectInputStream(is).readObject(); return object; } catch (Exception e) { throw new IciqlException(e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { throw new IciqlException(e); } } } }
private Reader getReader(Blob blob) throws SQLException, UnsupportedEncodingException { if (encoding == null) { return (new InputStreamReader(blob.getBinaryStream())); } else { return (new InputStreamReader(blob.getBinaryStream(), encoding)); } }
/* * (non-Javadoc) * @see org.datanucleus.store.rdbms.mapping.AbstractLargeBinaryRDBMSMapping#getObject(java.lang.Object, * int) */ @Override public Object getObject(ResultSet rs, int param) { byte[] bytes = null; try { // Retrieve the bytes of the object directly bytes = rs.getBytes(param); if (bytes == null) { return null; } } catch (SQLException sqle) { try { // Retrieve the bytes using the Blob (if getBytes not supported e.g HSQLDB 2.0) Blob blob = rs.getBlob(param); if (blob == null) { return null; } bytes = blob.getBytes(1, (int) blob.length()); if (bytes == null) { return null; } } catch (SQLException sqle2) { throw new NucleusDataStoreException( Localiser.msg("055002", "Object", "" + param, column, sqle2.getMessage()), sqle2); } } return getObjectForBytes(bytes, param); }
/** 读取数据库带图片的一条记录 */ @Test public void getImage() { Connection conn = null; Statement stmt = null; ResultSet rs = null; conn = JDBCUtils.getConnection(); try { stmt = conn.createStatement(); String sql = "select * from bt_user where id=1"; rs = stmt.executeQuery(sql); if (rs.next()) { Blob blob = rs.getBlob("headimage"); InputStream is = blob.getBinaryStream(); String path = "D:\\work\\Workspaces\\day14_jdbc\\src\\cn\\itcast\\mysql\\bt\\mm2.jpg"; OutputStream os = new FileOutputStream(path); byte[] buffer = new byte[1024]; int len = -1; while ((len = is.read(buffer)) != -1) { os.write(buffer, 0, len); } // os.flush(); os.close(); // close中有flush is.close(); } } catch (SQLException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { JDBCUtils.closeResource(conn, stmt, rs); } }
/** * Returns the bytes from a result set * * @param res The ResultSet to read from * @param columnName The name of the column to read from * @return The byte value from the column */ public byte[] getBytesFromBlob(Blob blob) throws SQLException { // read the bytes from an oracle blob // oracle.sql.BLOB blob = ((OracleResultSet) res).getBLOB(columnName); byte[] content = new byte[(int) blob.length()]; content = blob.getBytes(1, (int) blob.length()); return content; }
public byte[] getBytes(Blob img) throws SQLException { byte[] imgData = null; imgData = img.getBytes(1, (int) img.length()); return imgData; }
public InputStream getBlobStream(int columnIndex) throws SQLException { Blob blob = resultSet.getBlob(columnIndex + 1); if (blob == null) { return null; } else { return blob.getBinaryStream(); } }
@Override public InputStream getBinaryStream(final int columnIndex) throws SQLException { final Blob blob = getBlob(columnIndex); if (blob == null) { return null; } return blob.getBinaryStream(); }
public void testUpdateNew() throws Exception { Content content = addContent(); Blob data = content.getData(); assertFalse(data.getClass().equals(OutputBlob.class)); assertEquals(1024, data.length()); }
@Override protected byte[] getBlobAsBytes(ResultSet rs, int col) throws SQLException { if (_useBytesMethodsForBlob) { return rs.getBytes(col); } else { Blob dataAsBlob = rs.getBlob(col); return dataAsBlob.getBytes(1, (int) dataAsBlob.length()); } }
/** * Retrieves the byte position in the <code>BLOB</code> value designated by this <code>Blob</code> * object at which <code>pattern</code> begins. The search begins at position <code>start</code>. * * @param pattern the <code>Blob</code> object designating the <code>BLOB</code> value for which * to search * @param start the position in the <code>BLOB</code> value at which to begin searching; the first * position is 1 * @return the position at which the pattern begins, else -1 * @exception SQLException if there is an error accessing the <code>BLOB</code> value * @since JDK 1.2, HSQLDB 1.7.2 */ public long position(final Blob pattern, long start) throws SQLException { final byte[] ldata = data; final int dlen = ldata.length; if (start > dlen || pattern == null) { return -1; } else if (start < 1) { start = 0; } else { start--; } final long plen = pattern.length(); if (plen == 0 || start > ((long) dlen) - plen) { return -1; } // by now, we know plen <= Integer.MAX_VALUE final int iplen = (int) plen; byte[] bap; if (pattern instanceof jdbcBlob) { bap = ((jdbcBlob) pattern).data; } else { bap = pattern.getBytes(1, iplen); } final int stop = dlen - iplen; final byte b0 = bap[0]; outer_loop: for (int i = (int) start; i <= stop; i++) { if (ldata[i] != b0) { continue; } int len = iplen; int doffset = i; int poffset = 0; while (len-- > 0) { if (ldata[doffset++] != bap[poffset++]) { continue outer_loop; } } return i + 1; } return -1; }
public static String getBlobValue(ResultSet result, String strField) throws java.sql.SQLException { String strValueReturn = ""; Blob blob = result.getBlob(strField); if (result.wasNull()) { strValueReturn = ""; } else { int length = (int) blob.length(); if (length > 0) strValueReturn = new String(blob.getBytes(1, length)); } return strValueReturn; }
/** * Get value from given ResultSet at given index with given SQL type. * * @param rs The ResultSet to get the value from. * @param index The index of the value in the ResultSet. * @param sqlType The SQL type of the value. * @return The value. * @throws SQLException If a database access error occurs. */ public static Object getValue(final ResultSet rs, final int index, final int sqlType) throws SQLException { switch (sqlType) { case Types.CHAR: case Types.VARCHAR: case Types.LONGVARCHAR: return rs.getString(index); case Types.DECIMAL: case Types.NUMERIC: return rs.getBigDecimal(index); case Types.INTEGER: int intVal = rs.getInt(index); return (rs.wasNull() ? null : new Integer(intVal)); case Types.TIME: return rs.getTime(index, getCalendar()); case Types.DATE: return rs.getDate(index); case Types.TIMESTAMP: return rs.getTimestamp(index, getCalendar()); case Types.FLOAT: case Types.DOUBLE: double doubleVal = rs.getDouble(index); return (rs.wasNull() ? null : new Double(doubleVal)); case Types.REAL: float floatVal = rs.getFloat(index); return (rs.wasNull() ? null : new Float(floatVal)); case Types.SMALLINT: short shortVal = rs.getShort(index); return (rs.wasNull() ? null : new Short(shortVal)); case Types.TINYINT: byte byteVal = rs.getByte(index); return (rs.wasNull() ? null : new Byte(byteVal)); case Types.LONGVARBINARY: case Types.VARBINARY: case Types.BINARY: return rs.getBytes(index); case Types.BLOB: Blob blob = rs.getBlob(index); return (blob == null ? null : blob.getBinaryStream()); case Types.CLOB: return rs.getClob(index); case Types.BIGINT: long longVal = rs.getLong(index); return (rs.wasNull() ? null : new Long(longVal)); case Types.BIT: boolean boolVal = rs.getBoolean(index); return (rs.wasNull() ? null : new Boolean(boolVal)); default: Object value = rs.getObject(index); return (rs.wasNull() ? null : value); } }
static final <T> T transform( TeiidVersion teiidVersion, Object value, Class<T> targetType, Class<?> runtimeType) throws SQLException { if (value == null || targetType.isAssignableFrom(value.getClass())) { return targetType.cast(value); } if (targetType == byte[].class) { if (value instanceof Blob) { Blob blob = (Blob) value; long length = blob.length(); if (length > Integer.MAX_VALUE) { throw new SQLException( Messages.getString(Messages.JDBC.DataTypeTransformer_blob_too_big)); } return targetType.cast(blob.getBytes(1, (int) length)); } else if (value instanceof String) { return targetType.cast(((String) value).getBytes()); } else if (value instanceof BinaryTypeImpl) { return targetType.cast(((BinaryTypeImpl) value).getBytesDirect()); } } else if (targetType == String.class) { if (value instanceof SQLXML) { return targetType.cast(((SQLXML) value).getString()); } else if (value instanceof Clob) { Clob c = (Clob) value; long length = c.length(); if (length == 0) { // there is a bug in SerialClob with 0 length return targetType.cast(""); // $NON-NLS-1$ } return targetType.cast( c.getSubString(1, length > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) length)); } } try { DefaultDataTypeManager dataTypeManager = getDataTypeManager(teiidVersion); return (T) dataTypeManager.transformValue( dataTypeManager.convertToRuntimeType(value, true), runtimeType); } catch (Exception e) { String valueStr = value.toString(); if (valueStr.length() > 20) { valueStr = valueStr.substring(0, 20) + "..."; // $NON-NLS-1$ } String msg = Messages.getString( Messages.JDBC.DataTypeTransformer_Err_converting, valueStr, targetType.getSimpleName()); throw new SQLException(msg, e); } }
/** * Converts a LOB to the equivalent Java type, i.e. <code>Clob</code> to <code>String</code> and * <code>Blob</code> to <code>byte[]</code>. If the value passed is not a LOB object, it is left * unchanged and no exception is thrown; the idea is to transparently convert only LOBs. * * @param value an object that may be a LOB * @return if the value was a LOB, the equivalent Java object, otherwise the original value * @throws SQLException if an error occurs while reading the LOB contents */ public static Object convertLOB(Object value) throws SQLException { if (value instanceof Clob) { Clob c = (Clob) value; return c.getSubString(1, (int) c.length()); } if (value instanceof Blob) { Blob b = (Blob) value; return b.getBytes(1, (int) b.length()); } return value; }
private String getBase64OfBlob(java.sql.Blob b) { byte[] imageBytes = null; String imageEncoded64 = ""; try { imageBytes = b.getBytes(1, (int) b.length()); byte[] intermediate = Base64.encodeBase64(imageBytes); imageEncoded64 = new String(intermediate); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return imageEncoded64; }
/** * {@collect.stats} Constructs a <code>SerialBlob</code> object that is a serialized version of * the given <code>Blob</code> object. * * <p>The new <code>SerialBlob</code> object is initialized with the data from the <code>Blob * </code> object; therefore, the <code>Blob</code> object should have previously brought the SQL * <code>BLOB</code> value's data over to the client from the database. Otherwise, the new <code> * SerialBlob</code> object will contain no data. * * @param blob the <code>Blob</code> object from which this <code>SerialBlob</code> object is to * be constructed; cannot be null. * @throws SerialException if an error occurs during serialization * @throws SQLException if the <code>Blob</code> passed to this to this constructor is a <code> * null</code>. * @see java.sql.Blob */ public SerialBlob(Blob blob) throws SerialException, SQLException { if (blob == null) { throw new SQLException("Cannot instantiate a SerialBlob " + "object with a null Blob object"); } len = blob.length(); buf = blob.getBytes(1, (int) len); this.blob = blob; // if ( len < 10240000) // len = 10240000; origLen = len; }
/** * * bolob转为byte * * @param blob * @return * @throws Exception */ public static byte[] blob2ByteArr(Blob blob) { byte[] b = null; try { if (blob != null) { long in = 0; b = blob.getBytes(in, (int) (blob.length())); } } catch (Exception e) { e.printStackTrace(); } return b; }
@Test public void testStreaming() throws Exception { WSExecutionFactory ef = new WSExecutionFactory(); MetadataFactory mf = new MetadataFactory( "vdb", 1, "x", SystemMetadata.getInstance().getRuntimeTypeMap(), new Properties(), null); ef.getMetadata(mf, null); Procedure p = mf.getSchema().getProcedure(WSExecutionFactory.INVOKE_HTTP); assertEquals(7, p.getParameters().size()); TransformationMetadata tm = RealMetadataFactory.createTransformationMetadata(mf.asMetadataStore(), "vdb"); RuntimeMetadataImpl rm = new RuntimeMetadataImpl(tm); WSConnection mockConnection = Mockito.mock(WSConnection.class); Dispatch<Object> mockDispatch = mockDispatch(); DataSource mock = Mockito.mock(DataSource.class); ByteArrayInputStream baos = new ByteArrayInputStream(new byte[100]); Mockito.stub(mock.getInputStream()).toReturn(baos); Mockito.stub(mockDispatch.invoke(Mockito.any(DataSource.class))).toReturn(mock); Mockito.stub( mockConnection.createDispatch( Mockito.any(String.class), Mockito.any(String.class), Mockito.any(Class.class), Mockito.any(Service.Mode.class))) .toReturn(mockDispatch); CommandBuilder cb = new CommandBuilder(tm); Call call = (Call) cb.getCommand("call invokeHttp('GET', null, null, true)"); BinaryWSProcedureExecution pe = new BinaryWSProcedureExecution( call, rm, Mockito.mock(ExecutionContext.class), ef, mockConnection); pe.execute(); List<?> result = pe.getOutputParameterValues(); Blob b = (Blob) result.get(0); assertEquals(100, ObjectConverterUtil.convertToByteArray(b.getBinaryStream()).length); try { ObjectConverterUtil.convertToByteArray(b.getBinaryStream()); fail(); } catch (SQLException e) { // should only be able to read once } }
public void testBlobA() { try { String ddl0 = "DROP TABLE BLOBTEST IF EXISTS"; String ddl1 = "CREATE TABLE BLOBTEST(ID IDENTITY, BLOBFIELD BLOB(1000))"; statement.execute(ddl0); statement.execute(ddl1); } catch (SQLException e) { e.printStackTrace(); } try { String dml0 = "insert into blobtest(blobfield) values(?)"; String dql0 = "select * from blobtest;"; PreparedStatement ps = connection.prepareStatement(dml0); byte[] data = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; Blob blob = new JDBCBlob(data); ps.setBlob(1, blob); ps.executeUpdate(); data[4] = 50; blob = new JDBCBlob(data); ps.setBlob(1, blob); ps.executeUpdate(); ps.close(); ps = connection.prepareStatement(dql0); ResultSet rs = ps.executeQuery(); rs.next(); Blob blob1 = rs.getBlob(2); rs.next(); Blob blob2 = rs.getBlob(2); byte[] data1 = blob1.getBytes(1, 10); byte[] data2 = blob2.getBytes(1, 10); assertTrue(data1[4] == 5 && data2[4] == 50); } catch (SQLException e) { e.printStackTrace(); } }
public Feed(int id, String name, Blob icon, int unread) { this.id = id; this.name = name; try { this.icon = Base64.getEncoder().encodeToString(icon.getBytes(1, (int) icon.length())); if (this.icon.equals("") == false) { this.icon = "background-image: url(data:image/png;base64," + this.icon + ");"; } } catch (SQLException e) { e.printStackTrace(); } this.unread = unread; }
@Override public void releaseResources() { log.trace("Releasing JDBC resources"); for (Map.Entry<Statement, Set<ResultSet>> entry : xref.entrySet()) { if (entry.getValue() != null) { closeAll(entry.getValue()); } close(entry.getKey()); } xref.clear(); closeAll(unassociatedResultSets); if (blobs != null) { for (Blob blob : blobs) { try { blob.free(); } catch (SQLException e) { log.debugf("Unable to free JDBC Blob reference [%s]", e.getMessage()); } } blobs.clear(); } if (clobs != null) { for (Clob clob : clobs) { try { clob.free(); } catch (SQLException e) { log.debugf("Unable to free JDBC Clob reference [%s]", e.getMessage()); } } clobs.clear(); } if (nclobs != null) { for (NClob nclob : nclobs) { try { nclob.free(); } catch (SQLException e) { log.debugf("Unable to free JDBC NClob reference [%s]", e.getMessage()); } } nclobs.clear(); } }
public User mapRow(ResultSet rs, int rowNum) throws SQLException { long id = rs.getLong("userId"); if (isCacheEnabled() && lookupCache(cacheManager) != null) { Element element; if ((element = lookupCache(cacheManager).get(DbUtils.hashCodeCacheKeyFor(id))) != null) { log.debug("Cache hit on map for User " + id); return (User) element.getObjectValue(); } } User user = new UserImpl(); user.setUserId(id); user.setActive(rs.getBoolean("active")); user.setAdmin(rs.getBoolean("admin")); user.setExternal(rs.getBoolean("external")); user.setFullName(rs.getString("fullName")); user.setInternal(rs.getBoolean("internal")); user.setLoginName(rs.getString("loginName")); user.setPassword(rs.getString("password")); user.setEmail(rs.getString("email")); try { Blob roleblob = rs.getBlob("roles"); if (roleblob != null) { if (roleblob.length() > 0) { byte[] rbytes = roleblob.getBytes(1, (int) roleblob.length()); String s1 = new String(rbytes); String[] roles = s1.split(","); user.setRoles(roles); } } if (!isLazy()) { user.setGroups(listGroupsByUserId(id)); } } catch (IOException e) { e.printStackTrace(); } if (isCacheEnabled() && lookupCache(cacheManager) != null) { lookupCache(cacheManager).put(new Element(DbUtils.hashCodeCacheKeyFor(id), user)); } return user; }