如何将二进制文件存入Oracle数据库中

 我来答
司马刀剑
高粉答主

2018-11-16 · 每个回答都超有意思的
知道顶级答主
回答量:4.6万
采纳率:93%
帮助的人:7603万
展开全部
先把文件读取到内存,再以二进制格式保持到数据库中的大字段中(clob或clob)。
写大对象。

Java code

public static void main(String[] args) {
// TODO Auto-generated method stub
Connection conn = null;
Statement stat = null;
ResultSet rs = null;
OutputStream os = null;
FileInputStream fis = null;
int bs = 0;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:oraDB","bigfou","---");
conn.setAutoCommit(false);
stat = conn.createStatement();
stat.executeUpdate("insert into t_video(id,video) values(1,empty_blob())");

rs = stat.executeQuery("select video from t_video where id = 1");
rs.next();
oracle.sql.BLOB blo = (oracle.sql.BLOB)rs.getBlob(1);
os = blo.getBinaryOutputStream();
bs = blo.getBufferSize();
fis = new FileInputStream("D:\\Temp\\MPlayer-CVS-20040808-K&K\\mplayer.exe");
byte[] buf = new byte[bs];
int length = 0;

while(true)
{
length = fis.read(buf);
if(length == -1) break;
os.write(buf,0,length);
}

os.close();
os = null;
fis.close();
fis = null;
conn.commit();
conn.setAutoCommit(true);
conn.close();
} catch(Exception ex) {
ex.printStackTrace();
}
}

读大对象

Java code

InputStream is = null;
FileOutputStream fos = null;
byte[] buf = null;
int bs = 0;

try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:oraDB","bigfou","-");
conn.setAutoCommit(false);
stat = conn.createStatement();

rs = stat.executeQuery("select video from t_video where id = 1");
rs.next();
oracle.sql.BLOB blo = (oracle.sql.BLOB)rs.getBlob(1);
bs = blo.getBufferSize();
buf = new byte[bs];
int length = 0;
is = blo.getBinaryStream();
fos = new FileOutputStream("d:\\test.exe");

while(true) {
length = is.read(buf);
if(length == -1) break;
fos.write(buf,0,length);
}

fos.close();
fos = null;
is.close();
is = null;
conn.commit();
conn.setAutoCommit(true);
conn.close();
...
本回答被网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式