Java教程-在Oracle数据库中存储文件的示例

在Oracle数据库中存储文件的示例
PreparedStatement的setCharacterStream()方法用于将字符信息设置到参数索引中。
语法:
1) public void setBinaryStream(int paramIndex,InputStream stream)throws SQLException |
---|
2) public void setBinaryStream(int paramIndex,InputStream stream,long length)throws SQLException |
为了将文件存储到数据库中,在表中使用CLOB(字符大对象)数据类型。例如:
CREATE TABLE "FILETABLE"
( "ID" NUMBER,
"NAME" CLOB
)
/
Java示例:将文件存储在数据库中
import java.io.*;
import java.sql.*;
public class StoreFile {
public static void main(String[] args) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "oracle");
PreparedStatement ps = con.prepareStatement("insert into filetable values(?,?)");
File f = new File("d:\myfile.txt");
FileReader fr = new FileReader(f);
ps.setInt(1, 101);
ps.setCharacterStream(2, fr, (int) f.length());
int i = ps.executeUpdate();
System.out.println(i + " records affected");
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}