在derby(Java DB)中操作clob和blob
【IT168 技术文档】
在前面一篇文章《学习使用Java DataBase》中简单介绍了 derby 的使用,有朋友问我derby 只不支持blob和clob,我到官方网站看看,在参考文档中给出来一个例子,整理一下拿来做个例子,下面来看看如何在derby中操作clob的例子吧:
在《学习使用Java DataBase》的代码中加入如下一个方法:
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
0
相关文章
