您的位置:首页 > 数据库 > Oracle

HTML数据保存 Oracle CLOB大对象操作

2010-11-08 22:59 519 查看
public User getUser(int id) throws ClassNotFoundException, SQLException {
Connection conn = DBConnection.getConnection();
User user = new User();

try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from userinfo where id ="+id);
if (rs.next())
{
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setUserpass(rs.getString("userpass"));
java.sql.Clob clob = rs.getClob("userinfo");

Reader inStream = clob.getCharacterStream();
char[] c = new char[(int) clob.length()];
inStream.read(c);

String data = new String(c);
user.setUserinfo(data);
inStream.close();
}
rs.close();
stmt.close();
} catch (Exception e) {
System.out.println(" Error:"+e.getMessage());
}finally{
conn.close();
}
return user;
}
public int addUser(User user) throws ClassNotFoundException, SQLException {
Connection conn = DBConnection.getConnection();
String sql="";
int id = 0;

try {
PreparedStatement pstmt=null;
ResultSet rst=null;
conn.setAutoCommit(false);

oracle.sql.CLOB clob=null;

sql = "select sequenceDemo.nextval from dual";
pstmt = conn.prepareStatement(sql);
rst=pstmt.executeQuery();
if(rst.next()){
id = (int)rst.getInt(1);
}
pstmt.close();

//添加null Clob
sql = "insert into userinfo(id,username,userpass,userinfo) values (?,?,?,empty_clob())";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
pstmt.setString(2, user.getUsername());
pstmt.setString(3, user.getUserpass());

pstmt.executeUpdate();
pstmt.close();

//获取修改--锁
sql = "select userinfo from userinfo where id= ? for update";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
rst=pstmt.executeQuery();
if(rst.next()){
clob=(CLOB)rst.getClob(1);
}
pstmt.close();

//获得clob对象的输出流
PrintWriter pw=new PrintWriter(clob.getCharacterOutputStream());
pw.write(user.getUserinfo());
pw.flush();

//更新clob对象
sql="UPDATE userinfo set userinfo =? where id=?";
pstmt=conn.prepareStatement(sql);
pstmt.setClob(1, clob);
pstmt.setInt(2, id);

pstmt.executeUpdate();
conn.commit();

pw.close();
pstmt.close();
}catch (Exception e) {
System.out.println(" Error:"+e.getMessage());
}finally{
conn.close();
}
return id;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐