Sathish
Sathish

Reputation: 4713

convert Blob into a bytea in java

I'm working in postgresql database , i need to convert a MYSQL Blob datatype into a PostgreSQL bytea using java code only is there any way to do this?

Upvotes: 1

Views: 3297

Answers (2)

LaGrandMere
LaGrandMere

Reputation: 10379

//(assuming you have a ResultSet named RS)
PreparedStatement psMySql = connMySql.prepareStatement("select myBlob from myTable where ...");
Blob blob = rs.getBlob("myBlob");

int blobLength = (int) blob.length();  
byte[] blobAsBytes = blob.getBytes(1, blobLength);

PreparedStatement psPostresql = connPostgresql.prepareStatement("INSERT INTO myNewTable VALUES (?, ?)");
psPostresql.setString(1, myId);
psPostresql.setBytes(2, blobAsBytes);
psPostresql.executeUpdate();

//release the blob and free up memory.
blob.free();

Upvotes: 2

kovica
kovica

Reputation: 2583

As far as I know both support JDBC drivers. And JDBC has a standard way with dealing with BLOBs. I'm doing it all the time in DB2.

So:

  • connect to MySQL
  • do a select. Let's say the blob column is FIELD_BLOB
  • rs.getBytes("FIELD_BLOB")
  • connect to Postgres
  • do a PreparedStatement
  • call setBytes on this preparestatement passing in bytes you got from MySQL

If getBytes, setBytes does not work, try using input and output streams.

Upvotes: 0

Related Questions