How to create a java.sql.Blob object in Java SE 1.5.0 with a byte[] input?

余生颓废 提交于 2019-12-04 16:03:34

问题


I want to create a Blob object from a byte[] input to update a table using PreparedStatement#setBlob(). In J2SE 6, we have java.sql.Connection#createBlob() to get this done. Is there anything similar to this available in J2SE 1.5.0? What is the best way to update a BLOB type column with a byte[] data in J2SE 1.5.0?


回答1:


An example, using SerialBlob:

import java.sql.Blob;
import javax.sql.rowset.serial.SerialBlob;

byte[] byteArray = .....;
Blob blob = new SerialBlob(byteArray);



回答2:


You don't have to worry about creating Blob objects at all. Treat them as blobs on the database, and byte[]s in Java. For example:

@Entity
@Table(name = "some.table")
public class MyEntity
{
    @Id
    int myId;

    @Lob
    byte[] myBlob;

    // snip getters & setters
}

If you're really intent on creating a Blob instance yourself, you can use the SerialBlob implementation:

byte[] bytes = ...;
Blob myBlob = new SerialBlob(bytes);



回答3:


You don't need to actually create the Blob itself. When doing a prepared statement, use a ByteArrayInputStream for the parameter when setting the blob parameter.



来源:https://stackoverflow.com/questions/6278894/how-to-create-a-java-sql-blob-object-in-java-se-1-5-0-with-a-byte-input

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!