简体   繁体   中英

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.

I'm using jtds and tried to run:

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.

For reference, this is my Image class:

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?

Convert the byte array to a hex string, and provide the unquoted hex string in the SQL. Like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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