oracle数据库CLOB类型怎么转换为String
推荐于2017-11-24
import java.io.InputStream;
import java.io.Reader;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
public class TestClobOut {
public static void main(String args[]){
String data;
Reader inStream=null;
//获得数据库连接
Connection con = ConnectionFactory.getConnection();//ConnectionFactory类是另外定义的,不必纠结
con.setAutoCommit(false);
Statement st = con.createStatement();
//不需要“for update”
ResultSet rs = st.executeQuery("select CLOBATTR from TESTCLOB where ID=1");
if (rs.next())
{
java.sql.Clob clob = rs.getClob("CLOBATTR");
inStream = clob.getCharacterStream();
char[] c = new char[(int) clob.length()];
inStream.read(c);
//data是读出并需要返回的数据,类型是String
data = new String(c);
inStream.close();
}
inStream.close();
con.commit();
con.close();
}
}
给你段参考代码,读取clob数据
import java.io.InputStream;
import java.io.Reader;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
public class TestClobOut {
public static void main(String args[]){
String data;
Reader inStream=null;
//获得数据库连接Connection con = ConnectionFactory.getConnection();//ConnectionFactory类是另外定义的,不必纠结
con.setAutoCommit(false);
Statement st = con.createStatement();
//不需要“for update”
ResultSet rs = st.executeQuery("select CLOBATTR from TESTCLOB where ID=1");
if (rs.next())
{clob 转换 String (传入 clob 类型的 obj 对象)
public static String getClob2String(Object obj) {
String str = "";
try {
CLOB clob = (CLOB) obj;
if (clob == null || clob.length() == 0) {
str = "";
} else {
long clen = clob.length();
char clobArray[] = new char[(int) clen];
int readednum = clob.getChars(1, (int) clen, clobArray);
StringBuffer sb = new StringBuffer();
sb.append(clobArray);
str = sb.toString();
}
} catch (SQLException e) {
e.printStackTrace();
}
return str;
}
java.sql.Clob clob = rs.getClob("CLOBATTR");
inStream = clob.getCharacterStream();
char[] c = new char[(int) clob.length()];
inStream.read(c);
//data是读出并需要返回的数据,类型是String
data = new String(c);
inStream.close();
}
inStream.close();
con.commit();
con.close();
}
}