研究了一中午,终于把这个问题解决了!
1.创建test数据表(nclob好像不行,我改为clob了,不知是否影响你的使用?):
[code="java"]create table nclob_test (id number primary key, content clob);[/code]
2.java代码:
[code="java"]
public class TestClob{
public static void write_nclob(Connection con) throws SQLException,
IOException {
// 1.新增数据时clob字段值为empty_clob()
PreparedStatement smt = con
.prepareStatement("insert into nclob_test(id, content) values(?, empty_clob())");
smt.setInt(1, 1);
smt.executeUpdate();
smt.close();
//此处演示从文件中加载内容
File f = new File("e:\\促进企业节能增效.txt"); // 示例文件大小为200k
InputStream is = new FileInputStream(f);
byte[] data = new byte[(int) is.available()];
is.read(data);
is.close();
String buf = new String(data);
//写clob数据到数据库
update_nclob(con, buf);
}
public static void update_nclob(Connection con, String value) throws SQLException,
IOException {
// 此处注意用for update方式select
PreparedStatement smt = con
.prepareStatement("select id, content from nclob_test where id=1 for update");
// 更新clob值 注意必须将commit方式置为false
boolean old_c = con.getAutoCommit();
con.setAutoCommit(false);
ResultSet rs = smt.executeQuery();
if (rs.next()) {
Clob clob = rs.getClob(2);
BufferedWriter out = new BufferedWriter(((oracle.sql.CLOB) clob)
.getCharacterOutputStream());
BufferedReader in = new BufferedReader(new StringReader(value));
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
out.close();
con.commit();
smt.close();
}
con.setAutoCommit(old_c);
}
public static void load_nclob(Connection con) throws SQLException,
IOException {
PreparedStatement smt = con
.prepareStatement("select * from nclob_test");
ResultSet rs = smt.executeQuery();
if (rs.next()) {
Clob c = rs.getClob(2);
char[] cbuf = new char[4096];
c.getCharacterStream().read(cbuf);
String content = c.getSubString(1, (int) c.length());
// System.out.println(content);
System.out.println(new String(cbuf));
}
rs.close();
smt.close();
}
public static void main(String[] args) throws SQLException, IOException {
Connection con = 此处省略与数据库的连接,这个大家都会吧?!
write_nclob(con);
load_nclob(con);
}
}
[/code]