下面列出了java.sql.SQLData#java.sql.Clob 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public String getNullableResult(CallableStatement cs, int columnIndex)
throws SQLException {
String value = "";
Clob clob = cs.getClob(columnIndex);
if (clob != null) {
int size = (int) clob.length();
value = clob.getSubString(1, size);
}
return value;
}
public String format (Object value) {
Clob clob = (Clob) value;
StringBuilder sb = new StringBuilder();
char []chars = new char[512];
try {
Reader in = clob.getCharacterStream();
while (in.read(chars) >= 0) {
sb.append(chars);
}
in.close();
}
catch (Exception e) {
/* IGNORED */
}
return sb.toString();
}
/**
* Tests fix for BUG#20453671 - CLOB.POSITION() API CALL WITH CLOB INPUT RETURNS EXCEPTION
*
* @throws Exception
* if the test fails.
*/
public void testBug20453671() throws Exception {
this.rs = this.stmt.executeQuery("select 'abcd', 'a', 'b', 'c', 'd', 'e'");
this.rs.next();
final Clob in = this.rs.getClob(1);
final ResultSet locallyScopedRs = this.rs;
assertThrows(SQLException.class, "Illegal starting position for search, '0'", new Callable<Void>() {
public Void call() throws Exception {
in.position(locallyScopedRs.getClob(2), 0);
return null;
}
});
assertThrows(SQLException.class, "Starting position for search is past end of CLOB", new Callable<Void>() {
public Void call() throws Exception {
in.position(locallyScopedRs.getClob(2), 10);
return null;
}
});
assertEquals(1, in.position(this.rs.getClob(2), 1));
assertEquals(2, in.position(this.rs.getClob(3), 1));
assertEquals(3, in.position(this.rs.getClob(4), 1));
assertEquals(4, in.position(this.rs.getClob(5), 1));
assertEquals(-1, in.position(this.rs.getClob(6), 1));
}
/**
* Set the value from an non-null Java.sql.Clob object.
*/
void setObject(Object theValue)
throws StandardException
{
Clob vc = (Clob) theValue;
try {
long vcl = vc.length();
if (vcl < 0L || vcl > Integer.MAX_VALUE)
throw this.outOfRange();
setValue(new ReaderToUTF8Stream(vc.getCharacterStream(),
(int) vcl, 0, TypeId.CLOB_NAME), (int) vcl);
} catch (SQLException e) {
throw dataTypeConversion("DAN-438-tmp");
}
}
@Override
public Reader getClobAsCharacterStream(ResultSet rs, int columnIndex) throws SQLException {
logger.debug("Returning CLOB as character stream");
if (this.wrapAsLob) {
Clob clob = rs.getClob(columnIndex);
return clob.getCharacterStream();
}
else {
return rs.getCharacterStream(columnIndex);
}
}
public static String toString(Object[] args) {
if (args == null || args.length == 0) {
return "[]";
} else {
JsonArray out = new JsonArray();
for (int i = 0; i < args.length; i++) {
Object value = args[i];
if (value == null) {
out.add("null");
} else {
if (value instanceof String) {
String text = (String) value;
if (text.length() > 100) {
out.add(text.substring(0, 97) + "...");
} else {
out.add(text);
}
} else if (value instanceof Number) {
out.add((Number) value);
} else if (value instanceof Date) {
String str = DateUtils.formatDateTime((Date) value);
out.add(str);
} else if (value instanceof Boolean) {
out.add((Boolean) value);
} else if (value instanceof InputStream) {
out.add("<InputStream>");
} else if (value instanceof NClob) {
out.add("<NClob>");
} else if (value instanceof Clob) {
out.add("<Clob>");
} else if (value instanceof Blob) {
out.add("<Blob>");
} else {
out.add('<' + value.getClass().getName() + '>');
}
}
}
return out.toString();
}
}
protected void addBatchInsert(PreparedStatement stmt, int oid, int cid, int sid, int qty,
String status, Timestamp time, BigDecimal bid, int tid, boolean isPut) throws SQLException {
JSONObject json = new JSONObject();
String jsonLog ="";
if (SQLTest.hasJSON && ! SQLHelper.isDerbyConn(stmt.getConnection()) ) {
json = getJSONObject(oid,cid,sid,qty,status,time,bid,tid);
jsonLog = ",JSON_DETAILS: " +json.toJSONString();
}
Log.getLogWriter().info( (SQLHelper.isDerbyConn(stmt.getConnection())? "Derby - " :"gemfirexd - " ) + (isPut ? "putting " : "inserting ") + " into trade.buyorders with data OID:" + oid +
",CID:"+ cid + ",SID:" + sid + ",QTY:" + qty + ",STATUS:" + status +
",TIME:"+ time + ",BID:" + bid + ",TID:" + tid + jsonLog);
stmt.setInt(1, oid);
stmt.setInt(2, cid);
stmt.setInt(3, sid);
stmt.setInt(4, qty);
stmt.setBigDecimal(5, bid);
stmt.setTimestamp(6, time);
stmt.setString(7, status);
stmt.setInt(8, tid);
if (SQLTest.hasJSON && ! SQLHelper.isDerbyConn(stmt.getConnection()) ) { Clob jsonClob = stmt.getConnection().createClob();
jsonClob.setString(1, json.toJSONString());
stmt.setClob(9, jsonClob); }
stmt.addBatch();
}
@DataProvider(name = "testAdvancedParameters")
private Object[][] testAdvancedParameters() throws SQLException {
byte[] bytes = new byte[10];
Ref aRef = new SerialRef(new StubRef("INTEGER", query));
Array aArray = new SerialArray(new StubArray("INTEGER", new Object[1]));
Blob aBlob = new SerialBlob(new StubBlob());
Clob aClob = new SerialClob(new StubClob());
Reader rdr = new StringReader(query);
InputStream is = new StringBufferInputStream(query);;
brs = new StubBaseRowSet();
brs.setBytes(1, bytes);
brs.setAsciiStream(2, is, query.length());
brs.setRef(3, aRef);
brs.setArray(4, aArray);
brs.setBlob(5, aBlob);
brs.setClob(6, aClob);
brs.setBinaryStream(7, is, query.length());
brs.setUnicodeStream(8, is, query.length());
brs.setCharacterStream(9, rdr, query.length());
return new Object[][]{
{1, bytes},
{2, is},
{3, aRef},
{4, aArray},
{5, aBlob},
{6, aClob},
{7, is},
{8, is},
{9, rdr}
};
}
@Override
public InputStream getClobAsAsciiStream(ResultSet rs, int columnIndex) throws SQLException {
logger.debug("Returning Oracle CLOB as ASCII stream");
Clob clob = rs.getClob(columnIndex);
initializeResourcesBeforeRead(rs.getStatement().getConnection(), clob);
InputStream retVal = (clob != null ? clob.getAsciiStream() : null);
releaseResourcesAfterRead(rs.getStatement().getConnection(), clob);
return retVal;
}
@Override
public InputStream getClobAsAsciiStream(ResultSet rs, int columnIndex) throws SQLException {
logger.debug("Returning CLOB as ASCII stream");
if (this.wrapAsLob) {
Clob clob = rs.getClob(columnIndex);
return clob.getAsciiStream();
}
else {
return rs.getAsciiStream(columnIndex);
}
}
@Override
public Clob getClob(int parameterIndex) throws SQLException {
try {
if (this.wrappedStmt != null) {
return ((CallableStatement) this.wrappedStmt).getClob(parameterIndex);
}
throw SQLError.createSQLException(Messages.getString("Statement.AlreadyClosed"), MysqlErrorNumbers.SQL_STATE_GENERAL_ERROR,
this.exceptionInterceptor);
} catch (SQLException sqlEx) {
checkAndFireConnectionError(sqlEx);
}
return null;
}
@Override
public void setClobAsCharacterStream(
PreparedStatement ps, int paramIndex, Reader characterStream, int contentLength)
throws SQLException {
if (streamAsLob) {
if (characterStream != null) {
if (contentLength >= 0) {
ps.setClob(paramIndex, characterStream, contentLength);
}
else {
ps.setClob(paramIndex, characterStream);
}
}
else {
ps.setClob(paramIndex, (Clob) null);
}
}
else if (wrapAsLob) {
if (characterStream != null) {
ps.setClob(paramIndex, new PassThroughClob(characterStream, contentLength));
}
else {
ps.setClob(paramIndex, (Clob) null);
}
}
else if (contentLength >= 0) {
ps.setCharacterStream(paramIndex, characterStream, contentLength);
}
else {
ps.setCharacterStream(paramIndex, characterStream);
}
if (logger.isDebugEnabled()) {
logger.debug(characterStream != null ? "Set character stream for CLOB with length " + contentLength :
"Set CLOB to null");
}
}
private String readFromClob(Clob clob) {
Reader reader = FieldReaderDataSource.readCharStream(clob);
StringBuilder sb = new StringBuilder();
char[] buf = new char[1024];
int len;
try {
while ((len = reader.read(buf)) != -1) {
sb.append(buf, 0, len);
}
} catch (IOException e) {
DataImportHandlerException.wrapAndThrow(DataImportHandlerException.SEVERE, e);
}
return sb.toString();
}
@Override
public void setClobAsString(PreparedStatement ps, int paramIndex, String content)
throws SQLException {
if (streamAsLob) {
if (content != null) {
ps.setClob(paramIndex, new StringReader(content), content.length());
}
else {
ps.setClob(paramIndex, (Clob) null);
}
}
else if (wrapAsLob) {
if (content != null) {
ps.setClob(paramIndex, new PassThroughClob(content));
}
else {
ps.setClob(paramIndex, (Clob) null);
}
}
else {
ps.setString(paramIndex, content);
}
if (logger.isDebugEnabled()) {
logger.debug(content != null ? "Set string for CLOB with length " + content.length() :
"Set CLOB to null");
}
}
/**
* Tests the ClobWriter.write(String str, int off, int len) method
**/
public void testClobCharacterWrite3ParamString() throws Exception
{
PreparedStatement stmt3 = prepareStatement(
"SELECT c FROM testBlobX1 WHERE a = 1");
ResultSet rs3 = stmt3.executeQuery();
rs3.next();
Clob clob = rs3.getClob(1);
assertTrue("FAIL -- clob is NULL", clob != null);
Writer clobWriter = clob.setCharacterStream(1L);
clobWriter.write(unicodeTestString, 0, unicodeTestString.length());
clobWriter.close();
PreparedStatement stmt4 = prepareStatement(
"UPDATE testBlobX1 SET c = ? WHERE a = 1");
stmt4.setClob(1, clob);
stmt4.executeUpdate();
stmt4.close();
rs3.close();
rs3 = stmt3.executeQuery();
assertTrue("FAIL -- clob not found", rs3.next());
clob = rs3.getClob(1);
long new_length = clob.length();
assertEquals("FAIL -- wrong clob length", unicodeTestString.length(), new_length);
// Check contents ...
Reader lStream = clob.getCharacterStream();
assertTrue("FAIL - Clob and buffer contents do not match",
compareClobReader2CharArray(
unicodeTestString.toCharArray(),
lStream));
lStream.close();
rs3.close();
stmt3.close();
}
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;
}
@Override
public Clob getClob(int parameterIndex) throws SQLException {
synchronized (checkClosed().getConnectionMutex()) {
ResultSetInternalMethods rs = getOutputParameters(parameterIndex);
Clob retValue = rs.getClob(mapOutputParameterIndexToRsIndex(parameterIndex));
this.outputParamWasNull = rs.wasNull();
return retValue;
}
}
/**
* Tests fix for BUG#20453712 - CLOB.SETSTRING() WITH VALID INPUT RETURNS EXCEPTION
* server-side prepared statements and streaming BINARY data.
*
* @throws Exception
* if the test fails.
*/
public void testBug20453712() throws Exception {
final String s1 = "NewClobData";
this.rs = this.stmt.executeQuery("select 'a'");
this.rs.next();
final Clob c1 = this.rs.getClob(1);
// check with wrong position
assertThrows(SQLException.class, "Starting position can not be < 1", new Callable<Void>() {
public Void call() throws Exception {
c1.setString(0, s1, 7, 4);
return null;
}
});
// check with wrong substring index
assertThrows(SQLException.class, "String index out of range: 12", new Callable<Void>() {
public Void call() throws Exception {
c1.setString(1, s1, 8, 4);
return null;
}
});
// full replace
c1.setString(1, s1, 3, 4);
assertEquals("Clob", c1.getSubString(1L, (int) c1.length()));
// add
c1.setString(5, s1, 7, 4);
assertEquals("ClobData", c1.getSubString(1L, (int) c1.length()));
// replace middle chars
c1.setString(2, s1, 7, 4);
assertEquals("CDataata", c1.getSubString(1L, (int) c1.length()));
}
protected void getDataForUpdate(Connection conn, int[] cid, int[ ] cid2, int[] reps,
Clob[] profile, int[] whichUpdate, int size){
int numOfNonUniqUpdate = update.length/2;
reps = getReps(conn, size);
profile = getClob(size);
cid = getCustProfCid(conn, size);
cid2 = getCustProfCid(conn, size);
for (int i=0; i<size; i++) {
whichUpdate[i] = getWhichOne(numOfNonUniqUpdate, update.length);
}
}
@Override
public void updateClob(String columnLabel, Clob x) throws SQLException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void updateClob(int columnIndex, Clob x) throws SQLException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Clob getClob(int parameterIndex) throws SQLException
{
return _stmt.getClob(parameterIndex);
}
@Override
public void updateClob(int columnIndex, Clob x) throws SQLException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void updateClob(int columnIndex, Clob x) throws SQLException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setClob(int parameterIndex, Clob x) throws SQLException {
getDelegate().setClob(parameterIndex, x);
}
/**
* Tests fix for BUG#11614 - StringUtils.getBytes() doesn't work when using
* multibyte character encodings and a length in _characters_ is specified.
*
* @throws Exception
* if the test fails.
*/
public void testBug11614() throws Exception {
createTable("testBug11614",
"(`id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, `text` TEXT NOT NULL," + "PRIMARY KEY(`id`)) CHARACTER SET utf8 COLLATE utf8_general_ci");
Properties props = new Properties();
props.setProperty(PropertyKey.characterEncoding.getKeyName(), "utf8");
Connection utf8Conn = null;
try {
utf8Conn = getConnectionWithProps(props);
utf8Conn.createStatement().executeUpdate("INSERT INTO testBug11614 (`id`,`text`) values (1,'')");
this.rs = utf8Conn.createStatement().executeQuery("SELECT `text` FROM testBug11614 WHERE id=1");
assertTrue(this.rs.next());
Clob c = this.rs.getClob(1);
c.truncate(0);
int blockSize = 8192;
int sizeToTest = blockSize + 100;
StringBuilder blockBuf = new StringBuilder(sizeToTest);
for (int i = 0; i < sizeToTest; i++) {
blockBuf.append('\u00f6');
}
String valueToTest = blockBuf.toString();
c.setString(1, valueToTest);
this.pstmt = utf8Conn.prepareStatement("UPDATE testBug11614 SET `text` = ? WHERE id=1");
this.pstmt.setClob(1, c);
this.pstmt.executeUpdate();
this.pstmt.close();
String fromDatabase = getSingleIndexedValueWithQuery(utf8Conn, 1, "SELECT `text` FROM testBug11614").toString();
assertEquals(valueToTest, fromDatabase);
} finally {
if (utf8Conn != null) {
utf8Conn.close();
}
}
}
@Override
public void setClob(int i, Clob x) throws SQLException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void updateClob(int columnIndex, Clob x) {
throw new UnsupportedOperationException();
}
public Clob createClob() throws SQLException {
return delegate.createClob();
}
@Override
public Clob createClob() throws SQLException {
return connection.createClob();
}