通过JDBC,我们可以向oracle插入大对象,如图片,音频,长文本等,其插入方法有很多,这里演示一下通过流更新更新的形式插入CLOB大对象。
这是一个存储文本的例子,解释我会在程序中以注释的形式写出
/**
* 将生成的表样存储到数据库
*
* @param htmlParam
* @return
*/
public static boolean addToDB(HtmlParam htmlParam) {
//此处定义数据库操作时使用的对象
Connection conn = null;
//与查询操作在此函数中多次使用
PreparedStatement stmt = null;
ResultSet rs = null;
//ORACLE中的大对象
CLOB clob = null;
//写入大对象所需的流
Writer write = null;
try {
// jdbc连接数据库参数
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@192.168.1.210:1521:moe210";
conn = DriverManager.getConnection(url, "tjdemo", "tjdemo");
// 先插入相应的数据
String sql = "insert into html_demo values(SEQ_HTML.nextval, ?, ?, ?, ?, ?, ?, ?, empty_clob(), ?)";
//注意上一句插入的是一个空的大对象 empty_clob(),,即没有向大对象中插入任何数据
stmt = conn.prepareStatement(sql);
stmt.setInt(1, htmlParam.getProjectId());
stmt.setString(2, htmlParam.getReptName());
stmt.setInt(3, htmlParam.getStartRow());
stmt.setInt(4, htmlParam.getStartColumn());
stmt.setInt(5, htmlParam.getEndRow());
stmt.setInt(6, htmlParam.getEndColumn());
stmt.setString(7, htmlParam.getCharset());
stmt.setString(8, htmlParam.getPath());
stmt.executeUpdate();
// 查询当前sequence值,即查询刚刚插入到数据库中的字段的id
String seq = "select SEQ_HTML.currval from dual";
stmt = conn.prepareStatement(seq);
rs = stmt.executeQuery();
int id = 1;
if (rs.next()) {
id = rs.getInt(1);
}
//通过刚才查出的id我们可以 查询那个空的大对象
sql = "select html from html_demo where id=? for update";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, id);
rs = stmt.executeQuery();
//得到原来空的大对象
if (rs.next()) {
clob = (CLOB) rs.getClob(1);
}
// 通过流的形式更新大对象
write = clob.getCharacterOutputStream();
//将文本数据更新入大对象
write.write(htmlParam.getHtml());
//刷新缓存
write.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {//最后我们关闭资源
try {
if (write != null) {
write.close();
}
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return true;
}
我写的这个例子给出了插入大对象的基本操作和流程,相信你一定可以模仿完成自己的任务!