使用jdbc将查询出的clob大字段转string输出
直接上代码:
package org.ga.alipayRegulation.tools;
import java.io.IOException;
import java.io.Reader;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class ConnectionUntils {
private static Connection conn;
private ConnectionUntils(){
try {
throw new Exception("不能是实例");
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getInstance(){
if(conn == null){
initConnection();
}
return conn;
}
private static void initConnection() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");// 加载Oracle驱动程序
String url = "jdbc:oracle:thin:@123:1000:llb";//数据库链接
String user = "llb";
String password = "llb";
conn = DriverManager.getConnection(url, user, password);// 获取连接
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close(ResultSet rs, PreparedStatement pst, Connection connection) {
try {
if(rs!=null){
rs.close();
rs=null;
}
if(pst!=null){
pst.close();
pst=null;
}
if(connection!=null){
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/*
* 测试连接成功
*/
public static void main(String[] args) {
/*PreparedStatement pst = null;
ResultSet rs = null;
String sql = "select count(id) from cda_kity_mind ";
Connection con = getInstance();
try {
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
if(rs.next()){
System.out.println(rs.getInt(1));
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
close(rs,pst,con);
}*/
Connection conn = ConnectionUntils.getInstance();
String sql = " select content from test where id = ? ";//content是个clob大字段
PreparedStatement pst =null;
ResultSet rs = null;
try {
pst = conn.prepareStatement(sql);
pst.setInt(1,1);
rs = pst.executeQuery();
StringBuilder builder = new StringBuilder();
if(rs.next()){
Clob clob = rs.getClob("content");
Reader rd = clob.getCharacterStream();
char [] str = new char[12];
while(rd.read(str) != -1) {
builder.append(new String(str));
}
}
System.out.println(builder.toString());
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
ConnectionUntils.close(rs, pst, conn);
}
}
}