在前面一篇文章中,
http://www.blogjava.net/51AOP/archive/2006/04/13/40975.html
简单介绍了 derby 的使用,有朋友问我derby 只不支持 blob和clob, 我到官方网站看看,在参考文档中给出来一个例子,整理一下 那来做个例子, 下面来看看如何在derby中操作 clob的例子吧.
在前面代码中加入如下一个方法.
public Connection getConnection () {
return dbConnection;
}
创建一个测试clob的表 sql语句如下:
private static final String strCreateTestClobTeble =
"CREATE TABLE APP.documents (id INT, text CLOB(64 K))" ;
测试代码如下:
public static void main ( String [] args ) {
TestShutdown db = new TestShutdown () ;
System.out.println ( db.getDatabaseLocation ()) ;
System.out.println ( db.getDatabaseUrl ()) ;
long startTime = System.currentTimeMillis () ;
System.out.println ( startTime ) ;
db.connect () ;
// 测试clob 数据
File file = new File ( "test.txt" ) ;
int fileLenth = ( int ) file.length () ;
try {
// first ,create an inputStream
InputStream is = new FileInputStream ( file ) ;
PreparedStatement ps = db.getConnection () .prepareStatement ( "INSERT INTO APP.documents VALUES (?, ?)" ,Statement.RETURN_GENERATED_KEYS ) ;
ps.setInt ( 1 , 1477 ) ;
// - set the value of the input parameter to the input stream
ps.setAsciiStream ( 2 , is, fileLenth ) ;
ps.executeUpdate () ;
db.getConnection () .commit () ;
System.out.println ( "write clob data over! \n and now read it out." ) ;
//--- reading the columns
ResultSet rs = db.getConnection () .createStatement () .executeQuery ( "SELECT text FROM APP.documents WHERE id = 1477" ) ;
while ( rs.next ()) {
Clob clob = rs.getClob ( 1 ) ;
System.out.println ( clob.toString ()) ;
InputStream ip = rs.getAsciiStream ( 1 ) ;
int c = ip.read () ;
while ( c > 0 ) {
System.out.print (( char ) c ) ;
c = ip.read () ;
}
}
} catch ( FileNotFoundException e ) {
// TODO Auto-generated catch block
e.printStackTrace () ;
} catch ( SQLException e ) {
// TODO Auto-generated catch block
e.printStackTrace () ;
} catch ( IOException e ) {
}
db.disconnect () ;
}
可见 在derby中操作 clob数据和其他数据库是一样的,blob也是一样的 这里就不在测试了.
其实 derby的使用和其他的数据库(如: mysql)使用基本上是一样的, 支持标准的sql 语句和jdbc. 唯一不同的就是要 编程知道数据保存的位置,和 编程控制数据库的开启和关闭.
该测试的完整代码请点击: http://icess.tengyi.cn/opensource/Derby/src/testcolb.html
335

被折叠的 条评论
为什么被折叠?



