简体   繁体   English

如何在sql数据库中存储二进制文件?

[英]How do I store a binary file in an sql database?

I have a varbinary column we use to store excel files. 我有一个varbinary列,用于存储excel文件。 I need to update this column with the contents of a different xls file that is currently on my filesystem. 我需要使用当前在我的文件系统上的不同xls文件的内容更新此列。

Given a java.sql.Connection, how should I update the row? 给定java.sql.Connection,我应该如何更新行?

We are using sql server 2005. 我们正在使用sql server 2005。

I ended up doing the following: 我最后做了以下事情:

PreparedStatement st = conn.prepareStatement("update MyTable set binaryData = ? where id= 9");
st.setBinaryStream(1, new FileInputStream(file), (int)file.length());
st.execute();

Using a java.util.Connection and the correct SQL you could create an appropriate java.sql.PreparedStatement (I don't use SQL Server, so you'd be better writing the SQL yourself). 使用java.util.Connection和正确的SQL,您可以创建一个合适的java.sql.PreparedStatement(我不使用SQL Server,因此您最好自己编写SQL)。

You can create a java.sql.Blob using the byte data read from your xls file. 您可以使用从xls文件读取的字节数据创建java.sql.Blob。

Call .setBlob(Blob) on your PreparedStatement and then execute it. 在PreparedStatement上调用.setBlob(Blob)然后执行它。

I didn't write the code for you, but that should be the basics. 我没有为你编写代码,但这应该是基础知识。

将字节数组传递给BLOB字段。

在旧版本的Java中,您可以尝试

obj.setObject("@somefield", some_data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM