oracle在使用clob字段的时候一直无法写入数据库,在网上也找了很久,最后找到一种使用jdbc写入数据库的方式记录一下
实体类中我定义的是String类型
一:写入
public void updateStr(String newAddStr,String id){
Connection conn = DBHrlper.getMyConnection();//大家可以使用自己编写的JDBC连接
String sql = "UPDATE TABLE SET CONTENT = ? WHERE ID = ? ";
PreparedStatement ps;
try {
ps = conn.prepareStatement(sql);
Reader clobReader = new StringReader(newAddStr); // 将 text转成流形式
ps.setCharacterStream(1, clobReader, newAddStr.length());
ps.setString(2, id);
ps.executeUpdate();// 执行SQL
ps.close();
conn.close();
}catch (SQLException e) {
e.printStackTrace();
}
}
二:读取
/**
* 通过id读取该条数据
* @param id
* @return
*/
public ArticleEntity getContent(String id){
PreparedStatement ps =null;
ResultSet rs = null;
Connection conn = null;
Clob clob = null;
ArticleEntity aae = new ArticleEntity ();
String sql="SELECT * FROM TABLE WHERE ID = ? ";
try {
conn =DBHelper.getMyConnection();
ps = conn.prepareStatement(sql);
ps.setString(1, id);
rs = ps.executeQuery();
while(rs.next()){
aae.setId(rs.getString("ID"));
clob = (oracle.sql.CLOB) rs.getClob("CONTENT");
try {
if(clob !=null && clob != ""){
aae.setContent(ClobToString(clob));
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return aae;
}
/**
* 将字CLOB转成STRING类型
* @param clob
* @return
* @throws SQLException
* @throws IOException
*/
public String ClobToString(Clob clob) throws SQLException, IOException {
String reString = "";
Reader is = clob.getCharacterStream();// 得到流
BufferedReader br = new BufferedReader(is);
String s = br.readLine();
StringBuffer sb = new StringBuffer();
while (s != null) {
sb.append(s);
s = br.readLine();
}
reString = sb.toString();
return reString;
}