您的位置:首页 > 数据库

SQL小结(四)

2015-07-20 00:51 344 查看
数据库还可以储存大对象——图片或其他数据,二进制大对象为BOLB,字符型大对象为CLOB,以下为获取图像:


PreparedStatement stat = conn.prepareStatement("SELECT Cover FROM BookCovers WHERE ISBN =?");
stat.set(1.isbn);
ResultSet result = stat.executeQuery();
if(result.next()){
Blob coverBlob = result.getBlob(1);
Image coverImage = ImageIO.read(coverBlob.getBinaryStream());
}//CLOB调用getSubString或getCharacterStream方法


将该对象存储到数据库中:


Blob coverBlob = connection.createBlob();
in offset = 0;
OutputStream out = coverBlob.setBinaryStream(offset);
ImageIO.write(coverImage, "PNG", out);
PreparedStatement stat = conn.prepareStatement("INSERT INTO Cover VALUES (?, ?)");
stat.set(1,isbn);
stat.set(2,coverBlob);
stat.executeUpdate();


获取多结果集的步骤:
(1)使用execute方法来执行SQL语句
(2)获取第一个结果集或更新计数
(3)重复调用getMoreResults方法以移动到下一个结果集
(4)当不存在更多的结果集或更新计数时,完成操作
若果由多结果集构成的链中的下一项是结果集,execute和getMoreResults方法将返回true,而结果在链中的下一项不是更新计数,getUpdateCount方法讲返回-1


boolean isResult = stat.execute(command);
boolean done = false;
while(!done)
{
if(isResult)
{
ResultSet result = stat.getResultSet();
do something with result
}else{
int updateCount = stat.getUpdateCount();
if(updateCount >= 0)
do something with updateCount
else
done = ture;
}
if(!done) isResult = stat.getMoreReuslt();
}


可以通过如下方法创建不同的对象,得到滚动和更新结果集:


Statement stat = conn.createStatement(type, concurrency);
或PreparedStatement stat = conn.prepareStatement(command, type, concurrency);


(参数具体见图片解释)
如果涉及多个表的链接操作,那么他所产生的结果集将不可更新。可以调用ResultSet接口中的getConcurrency方法来确定结果集是否可更新
普通的更新操作:


Result rs = stat.executeQuery(query);
while(rs.next()){
if(```){
double price = rs.getDouble("Price");
rs.updateDouble("Price", price + increase);
rs.updateRow();//将信息更新到数据库
}
}


想在结果集中插入行:


rs.moveToInsertRow(); //将游标移动到特定位置——插入行
rs.updateString("Title",title);
rs.updateString("ISBN",isbn);
rs.updateString("Publisher_Id",pubid);
rs.updateDouble("Price",price);
rs.insertRow();
rs.moveToCurrentRow(); //将游标移动回原来的位置


行集无需像结果集一样时刻连接数据库,其中RowSet接口扩展自ResultSet接口,JAVA 7中获取行集方法


RowSetFactory factory = RowSetProvider.newFactory();
CachedRowSet crs = factory.createCachedRowSet();


通过行集建立数据库的链接:


crs.setURL("````");
crs.setUsername("```");
crs.setPassword("````");


设置语句和参数:


crs.setCommand("SELECT ```` ?");
crs.setString(1.publisherName);
crs.execute(); //这个方法会建立数据库连接,从而进行各种操作


在填充了行集后,数据中的数据发生了变化,造成数据不一致。参考实现会首先检查行集中的原始值是否与数据库中的一致。一致则修改,否则抛出SyncProviderException异常


4000
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  sql 数据库