简体   繁体   English

如何将字节数组存储到Java中的SQL Server varbinary(MAX)字段中?

[英]How to store a byte array into a SQL Server varbinary(MAX) field in Java?

I have an Android application that receives an image as byte array and I want to save it on my SQL Server database on a varbinary(MAX) field. 我有一个Android应用程序,它以字节数组形式接收图像,我想将其保存在SQL Server数据库的varbinary(MAX)字段中。

I'm using jtds and tried to run: 我正在使用jtds并尝试运行:

Statement statement = dbConnection.createStatement();
ResultSet result = statement.executeQuery(
   "INSERT INTO TB_IMAGE (ID, IMAGE) VALUES (" + image.getId() + "," + image.getImage() + ")")

I'm able to execute the query but it throws the following error: 我可以执行查询,但是会引发以下错误:

java.sql.SQLException: Invalid SQL statement or JDBC escape, terminating ']' not found.

Then I tried: 然后我尝试了:

String query = ("INSERT INTO TB_IMAGE (ID, IMAGE) VALUES (" + image.getId() + ", ?)");
PreparedStatement preparedStatement = dbConnection.prepareStatement(query);
preparedStatement.setBinaryStream(1, image.getImage());

But this requires a java.io.InputStream and the code does not compile. 但这需要java.io.InputStream,并且代码无法编译。

For reference, this is my Image class: 供参考,这是我的Image类:

public class Image {
    private int Id;
    private byte[] Image;

    public Image (int id) { this.Id = id; }

    public int getId() { return Id; }
    public void setId(int id) { Id = id; }

    public byte[] getImage() { return Image; }
    public void setImage(byte[] image) { Image = image; }
}

How can I save the image, a byte[], inside a varbinary(MAX) field? 如何将图像(byte [])保存在varbinary(MAX)字段中?

Convert the byte array to a hex string, and provide the unquoted hex string in the SQL. 将字节数组转换为十六进制字符串,并在SQL中提供未引用的十六进制字符串。 Like this: 像这样:

insert into tb_image(id, image) values(100, 0xaabbccdd11223344)

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

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