@Override public void readFields(ResultSet rs) throws SQLException { key = rs.getString("DOCUUID"); docuuid = rs.getString("DOCUUID"); // TODO: clob mutator how to determine the data base // ResultSetMetaData rsmd = rs.getMetaData(); // int ct = rsmd.getColumnType(2); // String cn = rsmd.getColumnName(2); // System.err.println("************************ "+cn+" "+ct); // boolean useClob = (rs.getMetaData().getColumnType(2) == java.sql.Types.CLOB); boolean useClob = true; if (useClob) { xml = null; try { Clob clob = rs.getClob("XML"); if (clob != null) { int n = (int) clob.length(); if (n > 0) xml = clob.getSubString(1, n); } } catch (Exception e) { xml = rs.getString("XML"); } } else { xml = rs.getString("XML"); } }
/** * Tests the implementation of getCharacterStream(long pos, long length). * * @throws Exception */ public void testGetCharacterStreamLong() throws Exception { String str1 = "This is a test String. This is a test String"; Reader r1 = new java.io.StringReader(str1); PreparedStatement ps = prepareStatement("insert into BLOBCLOB(ID, CLOBDATA) values(?,?)"); int id = BlobClobTestSetup.getID(); ps.setInt(1, id); ps.setCharacterStream(2, r1); ps.execute(); ps.close(); Statement st = createStatement(); ResultSet rs = st.executeQuery("select CLOBDATA from " + "BLOBCLOB where ID=" + id); rs.next(); Clob clob = rs.getClob(1); Reader r_1 = clob.getCharacterStream(2L, 5L); String str2 = str1.substring(1, 6); Reader r_2 = new java.io.StringReader(str2); assertEquals(r_2, r_1); rs.close(); st.close(); }
@SuppressWarnings("unchecked") public static final List<Record> build(Config config, ResultSet rs) throws SQLException { List<Record> result = new ArrayList<Record>(); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); String[] labelNames = new String[columnCount + 1]; int[] types = new int[columnCount + 1]; buildLabelNamesAndTypes(rsmd, labelNames, types); while (rs.next()) { Record record = new Record(); record.setColumnsMap(config.containerFactory.getColumnsMap()); Map<String, Object> columns = record.getColumns(); for (int i = 1; i <= columnCount; i++) { Object value; if (types[i] < Types.BLOB) value = rs.getObject(i); else if (types[i] == Types.CLOB) value = ModelBuilder.handleClob(rs.getClob(i)); else if (types[i] == Types.NCLOB) value = ModelBuilder.handleClob(rs.getNClob(i)); else if (types[i] == Types.BLOB) value = ModelBuilder.handleBlob(rs.getBlob(i)); else value = rs.getObject(i); columns.put(labelNames[i], value); } result.add(record); } return result; }
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(); st = conn.createStatement(); rs = st.executeQuery("select big_text from clob_test"); while (rs.next()) { Clob clob = rs.getClob("big_text"); // 读取大文本,方式1 Reader reader = clob.getCharacterStream(); // reader=rs.getCharacterStream(1); //读取大文本,方式2 // String s=rs.getString(1); //读取大文本,方式3 File file = new File("JdbcUtils.java"); Writer writer = new BufferedWriter(new FileWriter(file)); char[] buff = new char[1024]; // 缓冲区 for (int i = 0; (i = reader.read(buff)) > 0; ) writer.write(buff, 0, i); writer.close(); reader.close(); } } finally { JdbcUtils.free(rs, st, conn); } }
/* (non-Javadoc) * @see org.springframework.jdbc.core.RowMapper#mapRow(java.sql.ResultSet, int) */ @Override public Event mapRow(ResultSet rs, int rowNum) throws SQLException { Event event = new Event(); event.setPersistedId(rs.getLong("ID")); event.setTimestamp(rs.getTimestamp("EI_TIMESTAMP")); event.setEventType(EventTypeEnum.valueOf(rs.getString("EI_EVENT_TYPE"))); Originator originator = new Originator(); originator.setProcessId(rs.getString("ORIG_PROCESS_ID")); originator.setIp(rs.getString("ORIG_IP")); originator.setHostname(rs.getString("ORIG_HOSTNAME")); originator.setCustomId(rs.getString("ORIG_CUSTOM_ID")); originator.setPrincipal(rs.getString("ORIG_PRINCIPAL")); event.setOriginator(originator); MessageInfo messageInfo = new MessageInfo(); messageInfo.setMessageId(rs.getString("MI_MESSAGE_ID")); messageInfo.setFlowId(rs.getString("MI_FLOW_ID")); messageInfo.setPortType(rs.getString("MI_PORT_TYPE")); messageInfo.setOperationName(rs.getString("MI_OPERATION_NAME")); messageInfo.setTransportType(rs.getString("MI_TRANSPORT_TYPE")); event.setMessageInfo(messageInfo); event.setContentCut(rs.getBoolean("CONTENT_CUT")); try { event.setContent(IOUtils.toString(rs.getClob("MESSAGE_CONTENT").getAsciiStream())); } catch (IOException e) { throw new RuntimeException("Error reading content", e); } return event; }
/** * Obtains streams from the Clob and makes sure we can always read the last char in the Clob. * * <p>See DERBY-4060. * * @param id id of the Clob to use * @param length the length of the Clob * @param alphabet the alphabet used to create the content * @throws IOException if reading from a stream fails * @throws SQLException if something goes wrong */ private void getCharacterStreamLongLastChar(int id, int length, CharAlphabet alphabet) throws IOException, SQLException { // Get last char from the source stream. Reader cmpReader = new LoopingAlphabetReader(length, alphabet); cmpReader.skip(length - 1); char srcLastChar = (char) cmpReader.read(); assertTrue(cmpReader.read() == -1); PreparedStatement ps = prepareStatement("select CLOBDATA from BLOBCLOB where ID=?"); ps.setInt(1, id); // Read everything first. int charsToRead = length; ResultSet rs = ps.executeQuery(); rs.next(); Reader reader = rs.getClob(1).getCharacterStream(length - charsToRead + 1, charsToRead); // Drain the stream, and make sure we are able to read the last char. char lastCharRead = getLastCharInStream(reader, charsToRead); assertEquals(srcLastChar, lastCharRead); reader.close(); rs.close(); // Read a portion of the stream. charsToRead = length / 4; rs = ps.executeQuery(); rs.next(); reader = rs.getClob(1).getCharacterStream(length - charsToRead + 1, charsToRead); lastCharRead = getLastCharInStream(reader, charsToRead); assertEquals(srcLastChar, lastCharRead); reader.close(); rs.close(); // Read a very small portion of the stream. charsToRead = 1; rs = ps.executeQuery(); rs.next(); reader = rs.getClob(1).getCharacterStream(length - charsToRead + 1, charsToRead); lastCharRead = getLastCharInStream(reader, charsToRead); assertEquals(srcLastChar, lastCharRead); reader.close(); rs.close(); }
/** * Test that <code>Clob.getCharacterStream(long,long)</code> works on CLOBs that are streamed from * store. (DERBY-2891) */ public void testGetCharacterStreamLongOnLargeClob() throws Exception { getConnection().setAutoCommit(false); // create large (>32k) clob that can be read from store final int size = 33000; StringBuilder sb = new StringBuilder(size); for (int i = 0; i < size; i += 10) { sb.append("1234567890"); } final int id = BlobClobTestSetup.getID(); PreparedStatement ps = prepareStatement("insert into blobclob(id, clobdata) values (?,cast(? as clob))"); ps.setInt(1, id); ps.setString(2, sb.toString()); ps.executeUpdate(); ps.close(); Statement s = createStatement(); ResultSet rs = s.executeQuery("select clobdata from blobclob where id = " + id); assertTrue(rs.next()); Clob c = rs.getClob(1); // request a small region of the clob BufferedReader r = new BufferedReader(c.getCharacterStream(4L, 3L)); assertEquals("456", r.readLine()); r.close(); c.free(); rs.close(); s.close(); rollback(); }
// // Examine BLOBs and CLOBs. // private void vetLargeObjects( Connection conn, HashSet<String> unsupportedList, HashSet<String> notUnderstoodList) throws Exception { Statement stmt = conn.createStatement(); stmt.execute("CREATE TABLE t (id INT PRIMARY KEY, " + "b BLOB(10), c CLOB(10))"); stmt.execute( "INSERT INTO t (id, b, c) VALUES (1, " + "CAST (" + TestUtil.stringToHexLiteral("101010001101") + "AS BLOB(10)), CAST ('hello' AS CLOB(10)))"); ResultSet rs = stmt.executeQuery("SELECT id, b, c FROM t"); rs.next(); Blob blob = rs.getBlob(2); Clob clob = rs.getClob(3); vetObject(blob, unsupportedList, notUnderstoodList); vetObject(clob, unsupportedList, notUnderstoodList); stmt.close(); conn.rollback(); }
public String getClobValue(ResultSet rs, String column) throws SQLException { Clob clob = (Clob) rs.getClob(column); if (clob == null) return ""; BufferedReader in = null; try { in = new BufferedReader(clob.getReader()); StringBuffer sbuffer = new StringBuffer(); String str = in.readLine(); while (str != null) { sbuffer.append(str).append("\n"); str = in.readLine(); } return sbuffer.toString(); } catch (Exception e) { log.error("读取大字符串字段" + column + "失败", e); return null; } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } }
public static ArrayList<String> getClanAdmins(String clanName) { /** Returns uuids of players */ if (clanExists(clanName)) { ArrayList<String> Admins = new ArrayList<String>(); if (!(MySQL.mySQLenabled())) { Admins = (ArrayList<String>) ClansFile.getData().getStringList("Clans." + getClanNumber(clanName) + ".Admins"); } else { try { Connection conn = MySQL.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT clan,admins FROM CODClans"); ResultSet rs = ps.executeQuery(); while (rs.next()) { if (rs.getString("clan").equals(clanName)) { Admins = MySQL.stringToList(MySQL.clobToString(rs.getClob("admins"))); break; } } } catch (Exception e) { e.printStackTrace(); } } admins.put(clanName, Admins); return Admins; } ArrayList<String> newList = new ArrayList<String>(); admins.put(clanName, newList); return newList; }
public void testClobA() { try { String ddl0 = "DROP TABLE CLOBTEST IF EXISTS"; String ddl1 = "CREATE TABLE CLOBTEST(ID IDENTITY, CLOBFIELD CLOB(1000))"; statement.execute(ddl0); statement.execute(ddl1); } catch (SQLException e) { } try { String dml0 = "insert into clobtest(clobfield) values(?)"; String dql0 = "select * from clobtest;"; PreparedStatement ps = connection.prepareStatement(dml0); String data = "Testing blob insert and select ops"; Clob clob = new JDBCClob(data); ps.setClob(1, clob); ps.executeUpdate(); data = data.replaceFirst("insert", "INSERT"); clob = new JDBCClob(data); ps.setClob(1, clob); ps.executeUpdate(); ps.close(); ps = connection.prepareStatement(dql0); ResultSet rs = ps.executeQuery(); rs.next(); Clob clob1 = rs.getClob(2); rs.next(); Clob clob2 = rs.getClob(2); int data1 = clob1.getSubString(1, data.length()).indexOf("insert"); int data2 = clob2.getSubString(1, data.length()).indexOf("INSERT"); assertTrue(data1 == data2 && data1 > 0); } catch (SQLException e) { e.printStackTrace(); } }
/** * @throws IOException * @see com.tl.db.dialect.Dialect#getClob(java.sql.ResultSet, java.lang.String) */ public IClob getClob(ResultSet rs, String name) throws SQLException, IOException { Clob clob = rs.getClob(name); if (clob != null) { String content = LobHelper.readClob(clob); return LobHelper.createClob(content); } return null; }
@Override public Clob getClob(String colName) throws SQLException { try { return _res.getClob(colName); } catch (SQLException e) { handleException(e); return null; } }
@Override public Clob getClob(int i) throws SQLException { try { return _res.getClob(i); } catch (SQLException e) { handleException(e); return null; } }
/** * Inserts a Clob with the specified length, using a stream source, then fetches it from the * database and checks the length. * * @param length number of characters in the Clob * @throws IOException if reading from the source fails * @throws SQLException if something goes wrong */ private void insertAndFetchTest(long length) throws IOException, SQLException { PreparedStatement ps = prepareStatement("insert into BLOBCLOB(ID, CLOBDATA) values(?,?)"); int id = BlobClobTestSetup.getID(); ps.setInt(1, id); ps.setCharacterStream(2, new LoopingAlphabetReader(length), length); long tsStart = System.currentTimeMillis(); ps.execute(); println( "Inserted " + length + " chars (length specified) in " + (System.currentTimeMillis() - tsStart) + " ms"); Statement stmt = createStatement(); tsStart = System.currentTimeMillis(); ResultSet rs = stmt.executeQuery("select CLOBDATA from BLOBCLOB where id = " + id); assertTrue("Clob not inserted", rs.next()); Clob aClob = rs.getClob(1); assertEquals("Invalid length", length, aClob.length()); println("Fetched length (" + length + ") in " + (System.currentTimeMillis() - tsStart) + " ms"); rs.close(); // Insert same Clob again, using the lengthless override. id = BlobClobTestSetup.getID(); ps.setInt(1, id); ps.setCharacterStream(2, new LoopingAlphabetReader(length)); tsStart = System.currentTimeMillis(); ps.executeUpdate(); println( "Inserted " + length + " chars (length unspecified) in " + (System.currentTimeMillis() - tsStart) + " ms"); rs = stmt.executeQuery("select CLOBDATA from BLOBCLOB where id = " + id); assertTrue("Clob not inserted", rs.next()); aClob = rs.getClob(1); assertEquals("Invalid length", length, aClob.length()); println("Fetched length (" + length + ") in " + (System.currentTimeMillis() - tsStart) + " ms"); rs.close(); rollback(); }
/** * According to the JDBC spec, BLOB and CLOB objects must stay open even if the result set is * closed (see ResultSet.close). */ private void testLobStaysOpenUntilCommitted() throws Exception { Connection conn = getConnection(); stat = conn.createStatement(); stat.execute("create table test(id identity, c clob, b blob)"); PreparedStatement prep = conn.prepareStatement("insert into test values(null, ?, ?)"); prep.setString(1, ""); prep.setBytes(2, new byte[0]); prep.execute(); Random r = new Random(1); char[] chars = new char[100000]; for (int i = 0; i < chars.length; i++) { chars[i] = (char) r.nextInt(10000); } String d = new String(chars); prep.setCharacterStream(1, new StringReader(d), -1); byte[] bytes = new byte[100000]; r.nextBytes(bytes); prep.setBinaryStream(2, new ByteArrayInputStream(bytes), -1); prep.execute(); conn.setAutoCommit(false); ResultSet rs = stat.executeQuery("select * from test order by id"); rs.next(); Clob c1 = rs.getClob(2); Blob b1 = rs.getBlob(3); rs.next(); Clob c2 = rs.getClob(2); Blob b2 = rs.getBlob(3); assertFalse(rs.next()); // now close rs.close(); // but the LOBs must stay open assertEquals(0, c1.length()); assertEquals(0, b1.length()); assertEquals(chars.length, c2.length()); assertEquals(bytes.length, b2.length()); assertEquals("", c1.getSubString(1, 0)); assertEquals(new byte[0], b1.getBytes(1, 0)); assertEquals(d, c2.getSubString(1, (int) c2.length())); assertEquals(bytes, b2.getBytes(1, (int) b2.length())); stat.execute("drop table test"); conn.close(); }
public void getDescriptionsByWord(String sWord) throws SQLException, SAXException, IOException { String sSql = "SELECT description FROM hydc9 " + "WHERE ci = ?"; PreparedStatement statement = connection.prepareStatement(sSql); statement.setString(1, sWord); ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { controller.setDescriptionByWord(resultSet.getClob("description")); } resultSet.close(); statement.close(); }
/** * 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); } }
public static void loadOwnedPerks(Player p) { if (!(MySQL.mySQLenabled())) { List<String> perkNames = PerksFile.getData().getStringList("Perks.OwnedPerks." + p.getUniqueId()); ownedPerks.put(p, new ArrayList<Perk>()); for (int i = 0; i < perkNames.size(); i++) { String name = perkNames.get(i); if (getPerk(name) == Perk.NO_PERK) continue; ownedPerks.get(p).add(getPerk(name)); } } else { try { Connection conn = MySQL.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT uuid,list FROM CODPerks"); ResultSet rs = ps.executeQuery(); while (rs.next()) { if (rs.getString("uuid").equals(p.getUniqueId().toString())) { ArrayList<String> perkNames = MySQL.stringToList(MySQL.clobToString(rs.getClob("list"))); if ((perkNames == null) || (perkNames.isEmpty())) { ownedPerks.put(p, new ArrayList<Perk>()); } else { ownedPerks.put(p, new ArrayList<Perk>()); for (int i = 0; i < perkNames.size(); i++) { String name = perkNames.get(i); if (getPerk(name) == Perk.NO_PERK) continue; ownedPerks.get(p).add(getPerk(name)); } } break; } } if (ownedPerks.get(p) == null) { ownedPerks.put(p, new ArrayList<Perk>()); } rs.close(); ps.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } } }
public void getDescriptionsByCharacter(String sCharacter) throws SQLException, SAXException, IOException { String sSql = "SELECT hydc2.description FROM hydc2 AS hydc2, hydc3 AS hydc3 " + "WHERE hydc2.gbk = hydc3.gbk AND hydc3.unicode = ?"; PreparedStatement statement = connection.prepareStatement(sSql); statement.setInt(1, sCharacter.codePointAt(0)); ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { controller.setDescriptionByCharacter(resultSet.getClob("description")); } resultSet.close(); statement.close(); }
/** * Creates a list of items from ResultSet. * * @param rs ResultSet object created from query * @return list of created items */ public static List<Item> createItems(ResultSet rs) throws SQLException { List<Item> item = new LinkedList<Item>(); while (rs.next()) { Item newItem = new Item( rs.getInt("ITEM_ID"), rs.getString("NAME"), rs.getInt("PRICE"), rs.getInt("QUANT"), rs.getClob("DESCR")); item.add(newItem); } return item; }
/** * Executes the specified query two times, materializes the Clob on the first run and gets the * length through {@code Clob.length} on the second. * * <p>Note that the query must select a Clob column at index one and the length at index two. * * @param sql query to execute * @throws SQLException if the test fails for some reason */ private void fetchIterateGetLengthClob(String sql) throws SQLException { Statement stmt = createStatement(); ResultSet rs = stmt.executeQuery(sql); // Materialize the CLOB value. while (rs.next()) { assertEquals(rs.getInt(1), rs.getString(2).length()); } rs.close(); rs = stmt.executeQuery(sql); // Get the CLOB value length through Clob.length while (rs.next()) { assertEquals(rs.getInt(1), (int) rs.getClob(2).length()); } rs.close(); stmt.close(); }
/** * 对数据库返回的结果集的当前记录进行分析 * * @param rs 结果集 * @throws SQLException * @throws IOException * @throws DocumentException * @throws ParseException */ protected void parse(ResultSet rs) throws SQLException, IOException, DocumentException, ParseException { long t1 = -1; long t2 = -1; if (rs.getTimestamp("CI_CREATETIME") != null) t1 = rs.getTimestamp("CI_CREATETIME").getTime(); if (rs.getTimestamp("CI_LASTUPDATE") != null) t2 = rs.getTimestamp("CI_LASTUPDATE").getTime(); parse( rs.getInt("CI_OID"), rs.getInt("CI_PARENT_OID"), rs.getString("CI_ID"), t1, t2, rs.getInt("CI_STATUS"), rs.getInt("CI_TYPE_OID"), rs.getString("CI_ADMIN"), rs.getString("CI_NAME"), ResultSetOperation.clobToString(rs.getClob("CI_DATA"))); }
public CrawlResource getCrawlResourceDetail(Long resId) { CrawlResource resource = null; Connection conn = null; PreparedStatement pst = null; ResultSet rs = null; String sql = " select a.res_id,a.channel_id,a.res_title,a.res_link,a.res_content,a.res_text,to_char(a.create_time,'yyyy-mm-dd hh24:mi:ss') create_time,a.res_status,a.res_img_path_set,a.res_file_path_set from twap_public_crawl_resource a where a.res_id = ? "; try { conn = JavaOracle.getConn(); pst = conn.prepareStatement(sql); pst.setLong(1, resId); rs = pst.executeQuery(); if (rs.next()) { Clob clob = rs.getClob("res_text"); Reader inStream = clob.getCharacterStream(); char[] c = new char[(int) clob.length()]; inStream.read(c); // data是读出并需要返回的数据,类型是String String data = new String(new String(c).getBytes(), "GBK"); inStream.close(); resource = new CrawlResource(); resource.setChannelId(rs.getLong("channel_id")); resource.setContent(data); resource.setCreateTime(rs.getString("create_time")); resource.setLink(rs.getString("res_link")); resource.setResId(rs.getLong("res_id")); resource.setStatus(rs.getString("res_status")); resource.setTitle(rs.getString("res_title")); resource.setImgPathSet(rs.getString("res_img_path_set")); resource.setFilePathSet(rs.getString("res_file_path_set")); } } catch (Exception e) { e.printStackTrace(); } finally { close(conn, pst, rs); } return resource; }
/** * Insert a row with a large clob into the test table. Read the row from the database and assign * the clob value to <code>clob</code>. * * @return The id of the row that was inserted * @throws java.sql.SQLException */ private int initializeLongClob() throws SQLException { // Clob needs to be larger than one page for locking to occur final int lobLength = 40000; // Insert a long Clob PreparedStatement ps = prepareStatement("insert into BLOBCLOB(ID, CLOBDATA) values(?,?)"); int id = BlobClobTestSetup.getID(); ps.setInt(1, id); ps.setCharacterStream(2, new LoopingAlphabetReader(lobLength), lobLength); ps.execute(); ps.close(); commit(); // Fetch the Clob object from the database Statement st = createStatement(); ResultSet rs = st.executeQuery("select CLOBDATA from BLOBCLOB where ID=" + id); rs.next(); clob = rs.getClob(1); rs.close(); st.close(); return id; }
@SuppressWarnings("unchecked") private static <T> T getFromResultSet(ExecuteContext ctx, Class<? extends T> type, int index) throws SQLException { ResultSet rs = ctx.resultSet(); if (type == Blob.class) { return (T) rs.getBlob(index); } else if (type == Boolean.class) { return (T) checkWasNull(rs, Boolean.valueOf(rs.getBoolean(index))); } else if (type == BigInteger.class) { // The SQLite JDBC driver doesn't support BigDecimals if (ctx.getDialect() == SQLDialect.SQLITE) { return Convert.convert(rs.getString(index), (Class<? extends T>) BigInteger.class); } else { BigDecimal result = rs.getBigDecimal(index); return (T) (result == null ? null : result.toBigInteger()); } } else if (type == BigDecimal.class) { // The SQLite JDBC driver doesn't support BigDecimals if (ctx.getDialect() == SQLDialect.SQLITE) { return Convert.convert(rs.getString(index), (Class<? extends T>) BigDecimal.class); } else { return (T) rs.getBigDecimal(index); } } else if (type == Byte.class) { return (T) checkWasNull(rs, Byte.valueOf(rs.getByte(index))); } else if (type == byte[].class) { return (T) rs.getBytes(index); } else if (type == Clob.class) { return (T) rs.getClob(index); } else if (type == Date.class) { return (T) getDate(ctx.getDialect(), rs, index); } else if (type == Double.class) { return (T) checkWasNull(rs, Double.valueOf(rs.getDouble(index))); } else if (type == Float.class) { return (T) checkWasNull(rs, Float.valueOf(rs.getFloat(index))); } else if (type == Integer.class) { return (T) checkWasNull(rs, Integer.valueOf(rs.getInt(index))); } else if (type == Long.class) { return (T) checkWasNull(rs, Long.valueOf(rs.getLong(index))); } else if (type == Short.class) { return (T) checkWasNull(rs, Short.valueOf(rs.getShort(index))); } else if (type == String.class) { return (T) rs.getString(index); } else if (type == Time.class) { return (T) getTime(ctx.getDialect(), rs, index); } else if (type == Timestamp.class) { return (T) getTimestamp(ctx.getDialect(), rs, index); } else if (type == YearToMonth.class) { if (ctx.getDialect() == POSTGRES) { Object object = rs.getObject(index); return (T) (object == null ? null : PostgresUtils.toYearToMonth(object)); } else { String string = rs.getString(index); return (T) (string == null ? null : YearToMonth.valueOf(string)); } } else if (type == DayToSecond.class) { if (ctx.getDialect() == POSTGRES) { Object object = rs.getObject(index); return (T) (object == null ? null : PostgresUtils.toDayToSecond(object)); } else { String string = rs.getString(index); return (T) (string == null ? null : DayToSecond.valueOf(string)); } } else if (type == UByte.class) { String string = rs.getString(index); return (T) (string == null ? null : UByte.valueOf(string)); } else if (type == UShort.class) { String string = rs.getString(index); return (T) (string == null ? null : UShort.valueOf(string)); } else if (type == UInteger.class) { String string = rs.getString(index); return (T) (string == null ? null : UInteger.valueOf(string)); } else if (type == ULong.class) { String string = rs.getString(index); return (T) (string == null ? null : ULong.valueOf(string)); } // The type byte[] is handled earlier. byte[][] can be handled here else if (type.isArray()) { switch (ctx.getDialect()) { case POSTGRES: { return pgGetArray(ctx, type, index); } default: // Note: due to a HSQLDB bug, it is not recommended to call rs.getObject() here: // See https://sourceforge.net/tracker/?func=detail&aid=3181365&group_id=23316&atid=378131 return (T) convertArray(rs.getArray(index), (Class<? extends Object[]>) type); } } else if (ArrayRecord.class.isAssignableFrom(type)) { return (T) getArrayRecord(ctx, rs.getArray(index), (Class<? extends ArrayRecord<?>>) type); } else if (EnumType.class.isAssignableFrom(type)) { return getEnumType(type, rs.getString(index)); } else if (MasterDataType.class.isAssignableFrom(type)) { return (T) getMasterDataType(type, rs.getObject(index)); } else if (UDTRecord.class.isAssignableFrom(type)) { switch (ctx.getDialect()) { case POSTGRES: return (T) pgNewUDTRecord(type, rs.getObject(index)); } return (T) rs.getObject(index, DataTypes.udtRecords()); } else if (Result.class.isAssignableFrom(type)) { ResultSet nested = (ResultSet) rs.getObject(index); return (T) getNewFactory(ctx).fetch(nested); } else { return (T) rs.getObject(index); } }
protected static Element createRow(ResultSet rs, ResultSetMetaData metaData, Element rootElement) throws SQLException, IOException { Document doc = rootElement.getOwnerDocument(); Element rowElement = doc.createElement(SQLSchemaGenerator.ROW_ELEMENT); rootElement.appendChild(rowElement); int columnCount = metaData.getColumnCount(); for (int i = 1; i <= columnCount; i++) { int type = metaData.getColumnType(i); String columnName = metaData.getColumnName(i); if (columnName == null) columnName = ""; Element colElement = doc.createElement(columnName.toLowerCase()); rowElement.appendChild(colElement); switch (type) { case java.sql.Types.CHAR: case java.sql.Types.VARCHAR: case java.sql.Types.LONGVARCHAR: // case java.sql.Types.NCHAR: // case java.sql.Types.NVARCHAR: // case java.sql.Types.LONGNVARCHAR: String content = rs.getString(i); colElement.appendChild(doc.createTextNode(content == null ? "" : content)); break; case java.sql.Types.NUMERIC: case java.sql.Types.DECIMAL: int scale = metaData.getScale(i); if (scale <= 0) { // 按照整数处理 Long l = rs.getLong(i); colElement.appendChild(doc.createTextNode(l == null ? "" : l.toString())); } else { // 按照double处理 Double d = rs.getDouble(i); colElement.appendChild(doc.createTextNode(d == null ? "" : d.toString())); } break; case java.sql.Types.BOOLEAN: case java.sql.Types.BIT: Boolean b = rs.getBoolean(i); colElement.appendChild(doc.createTextNode(b == null ? "" : b.toString())); break; case java.sql.Types.TINYINT: case java.sql.Types.SMALLINT: case java.sql.Types.INTEGER: Integer theInt = rs.getInt(i); colElement.appendChild(doc.createTextNode(theInt == null ? "" : theInt.toString())); break; case java.sql.Types.BIGINT: Long theLong = rs.getLong(i); colElement.appendChild(doc.createTextNode(theLong == null ? "" : theLong.toString())); break; case java.sql.Types.REAL: Float f = rs.getFloat(i); colElement.appendChild(doc.createTextNode((f == null ? "" : f.toString()))); break; case java.sql.Types.FLOAT: case java.sql.Types.DOUBLE: Double db = rs.getDouble(i); colElement.appendChild(doc.createTextNode(db == null ? "" : db.toString())); break; case java.sql.Types.BINARY: case java.sql.Types.VARBINARY: case java.sql.Types.LONGVARBINARY: byte[] bytes = rs.getBytes(i); if (bytes != null) { String base64 = new String(Base64.encodeBase64(bytes), "UTF-8"); colElement.appendChild(doc.createCDATASection(base64)); } case java.sql.Types.BLOB: Blob blob = rs.getBlob(i); if (blob != null) { InputStream in = blob.getBinaryStream(); if (in != null) { byte[] tyeBytes = new byte[in.available()]; int offset = 0; int numRead = 0; while (offset < tyeBytes.length && (numRead = in.read(tyeBytes, offset, tyeBytes.length - offset)) >= 0) { offset += numRead; } String base64_2 = new String(Base64.encodeBase64(tyeBytes), "UTF-8"); colElement.appendChild(doc.createCDATASection(base64_2)); } } break; case java.sql.Types.CLOB: Clob clob = rs.getClob(i); if (clob != null) { InputStream clobIn = clob.getAsciiStream(); if (clobIn != null) { byte[] clobBytes = new byte[clobIn.available()]; int clob_offset = 0; int clob_numRead = 0; while (clob_offset < clobBytes.length && (clob_numRead = clobIn.read(clobBytes, clob_offset, clobBytes.length - clob_offset)) >= 0) { clob_offset += clob_numRead; } String base64_3 = new String(Base64.encodeBase64(clobBytes), "UTF-8"); colElement.appendChild(doc.createCDATASection(base64_3)); } } break; case java.sql.Types.DATE: java.sql.Date sqlDate = rs.getDate(i); colElement.appendChild(doc.createTextNode(sqlDate == null ? "" : sqlDate.toString())); break; case java.sql.Types.TIME: java.sql.Time t = rs.getTime(i); colElement.appendChild(doc.createTextNode(t == null ? "" : t.toString())); break; case java.sql.Types.TIMESTAMP: java.sql.Timestamp ts = rs.getTimestamp(i); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); colElement.appendChild(doc.createTextNode(ts == null ? "" : df.format(ts))); break; } } return rowElement; }
public Clob getClob(String colName) throws SQLException { return rs.getClob(colName); }
public Clob getClob(int i) throws SQLException { return rs.getClob(i); }