Java blob to text

Как конвертировать Blob в строку и String в Blob в Java

Он работает нормально, но когда я собираюсь конвертировать String в Blob и пытается вставить в базу данных, то ничего не вставляя в базу данных. Я использовал приведенный ниже код для преобразования String в Blob:

String value = (s); byte[] buff = value.getBytes(); Blob blob = new SerialBlob(buff); 

Может ли кто-нибудь помочь мне о преобразовании Blob в String а также String в Blob на яве?

6 ответов

Попробуйте это (a2 — BLOB col)

PreparedStatement ps1 = conn.prepareStatement("update t1 set a2=? where blob = conn.createBlob(); blob.setBytes(1, str.getBytes()); ps1.setBlob(1, blob); ps1.executeUpdate(); 

он может работать даже без BLOB, драйвер автоматически преобразует типы:

 ps1.setBytes(1, str.getBytes); ps1.setString(1, str); 

Кроме того, если вы работаете с текстом, CLOB кажется более естественным типом col

Используйте это, чтобы конвертировать String в Blob. Где соединение — это соединение с объектом БД.

 String strContent = s; byte[] byteConent = strContent.getBytes(); Blob blob = connection.createBlob();//Where connection is the connection to db object. blob.setBytes(1, byteContent); 

Как вы устанавливаете BLOB в БД? Ты должен сделать:

 //imagine u have a a prepared statement like: PreparedStatement ps = conn.prepareStatement("INSERT INTO table VALUES (?)"); String blobString= "This is the string u want to convert to Blob"; oracle.sql.BLOB myBlob = oracle.sql.BLOB.createTemporary(conn, false,oracle.sql.BLOB.DURATION_SESSION); byte[] buff = blobString.getBytes(); myBlob.putBytes(1,buff); ps.setBlob(1, myBlob); ps.executeUpdate(); 

И вот мое решение, которое всегда работает для меня

StringBuffer buf = new StringBuffer(); String temp; BufferedReader bufReader = new BufferedReader(new InputStreamReader(myBlob.getBinaryStream())); while ((temp=bufReader.readLine())!=null)

Вот мое решение:

Получите столбец BLOB-объекта из базы данных и передайте его указанному ниже методу.

 public static String blobToString(BLOB blob) throws Exception < byte[] data = new byte[(int) blob.length()]; BufferedInputStream instream = null; try < instream = new BufferedInputStream(blob.getBinaryStream()); instream.read(data); >catch (Exception ex) < throw new Exception(ex.getMessage()); >finally < instream.close(); >int chunk = 65536; ByteArrayInputStream bis = new ByteArrayInputStream(data); GZIPInputStream gis = new GZIPInputStream(bis); int length = 0; byte[] buffer = new byte[chunk]; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while ((length = gis.read(buffer, 0, chunk)) != -1) < bos.write(buffer, 0, length); >gis.close(); bis.close(); bos.close(); String str = bos.toString(); System.out.println(str); return str; > 

Источник

How to convert blob to string and string to blob in java?

Blob and String are two common data types in Java that are used to store and retrieve data from a database. Blob stands for Binary Large Object and is used to store binary data, while String is a sequence of characters. However, sometimes it may be necessary to convert Blob to String or vice versa to store or retrieve data from a database. In this article, we will discuss how to convert Blob to String and String to Blob in Java.

Method 1: Using getBytes() method

Converting Blob to String

Blob blob = resultSet.getBlob("blob_column"); String blobAsString = new String(blob.getBytes(1, (int) blob.length()));

In the above code, we first retrieve the Blob object from the ResultSet using the column name. Then we convert the Blob object to a byte array using the getBytes() method. Finally, we create a new String object from the byte array.

Converting String to Blob

String string = "This is a sample string"; byte[] stringAsBytes = string.getBytes(); Blob blob = new SerialBlob(stringAsBytes);

In the above code, we first convert the String object to a byte array using the getBytes() method. Then we create a new Blob object using the SerialBlob class constructor, passing in the byte array as a parameter.

Note: The SerialBlob class is used to create a Blob object from a byte array. If you want to create a Blob object from a File or InputStream , you can use the Blob interface’s setBinaryStream() method.

That’s it! These are the steps to convert Blob to String and String to Blob in Java using the getBytes() method.

Method 2: Using Apache Commons IOUtils

import org.apache.commons.io.IOUtils; Blob blob = resultSet.getBlob("blob_column_name"); String str = IOUtils.toString(blob.getBinaryStream(), "UTF-8");
  1. Import the org.apache.commons.io.IOUtils package.
  2. Get the Blob object from the ResultSet .
  3. Convert the Blob object to a String object using the IOUtils.toString() method.
  4. Pass the Blob object’s binary stream and the encoding type to the IOUtils.toString() method.
import org.apache.commons.io.IOUtils; String str = "This is a string"; InputStream inputStream = IOUtils.toInputStream(str, "UTF-8"); Blob blob = Hibernate.getLobCreator(session).createBlob(inputStream, inputStream.available());
  1. Import the org.apache.commons.io.IOUtils package.
  2. Create a String object.
  3. Convert the String object to an InputStream object using the IOUtils.toInputStream() method.
  4. Create a Blob object using the Hibernate.getLobCreator() method.
  5. Pass the InputStream object and its length to the createBlob() method.

Note: Hibernate.getLobCreator(session) is used to create a LobCreator instance, which is used to create Blob and Clob objects. If you are not using Hibernate, you can create a Blob object using the java.sql.Blob interface.

That’s it! You have successfully converted a Blob object to a String object and a String object to a Blob object using Apache Commons IOUtils.

Method 3: Using Java 8’s Base64 Encoding

To convert a Blob to a String using Java 8’s Base64 Encoding, you can follow these steps:

  1. Get the Blob data as a byte array using the getBytes() method.
  2. Encode the byte array using Base64.getEncoder().encodeToString() method to get a String representation of the data.
Blob blob = resultSet.getBlob("blob_column"); byte[] blobData = blob.getBytes(1, (int) blob.length()); String encodedString = Base64.getEncoder().encodeToString(blobData);

To convert a String to a Blob using Java 8’s Base64 Encoding, you can follow these steps:

  1. Decode the String using Base64.getDecoder().decode() method to get a byte array.
  2. Create a new Blob object using the byte array using connection.createBlob() method.
String encodedString = "base64_encoded_string"; byte[] decodedBytes = Base64.getDecoder().decode(encodedString); Blob blob = connection.createBlob(); blob.setBytes(1, decodedBytes);

Источник

How to convert Blob to String and String to Blob in java

Can anyone help me about to converting of Blob to String and String to Blob in Java?,To convert Blob to String in Java:,Thanks for contributing an answer to Stack Overflow!,Use this to convert String to Blob. Where connection is the connection to db object.

PreparedStatement ps1 = conn.prepareStatement("update t1 set a2=? where blob = conn.createBlob(); blob.setBytes(1, str.getBytes()); ps1.setBlob(1, blob); ps1.executeUpdate(); 

it may work even without BLOB, driver will transform types automatically:

 ps1.setBytes(1, str.getBytes); ps1.setString(1, str); 

Answer by Bella Sampson

getBinaryStreamRetrieves length bytes from this Blob, starting at 1-based offset pos, and returns them as a binary ,Timestamp (java.sql)A Java representation of the SQL TIMESTAMP type. It provides the capability of representing the SQL ,positionSearch for the position in this Blob at which the specified pattern begins, starting at a specified ,setBinaryStreamGets a stream that can be used to write binary data to this Blob.

Answer by Eva Zavala

You can contents of a blob into a byte array using the getBytes() method.,How to convert a byte array to hex string in Java?,How to convert hex string to byte Array in Java?,How to convert an input stream to byte array in java?

Example

import java.awt.Image; import java.awt.image.BufferedImage; import java.sql.Blob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.Arrays; public class BlobToByteArray < public static void main(String[] args) throws Exception < Image image = new BufferedImage(300,400, BufferedImage.TYPE_INT_RGB); String JDBC_DRIVER = "com.mysql.jdbc.Driver"; String DB_URL = "jdbc:mysql://localhost/mydb"; String USER = "root"; String PASS = "password"; Connection conn = null; Statement stmt = null; Class.forName("com.mysql.jdbc.Driver"); System.out.println("Connecting to a selected database. "); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Connected database successfully. "); System.out.println("getting blob. "); stmt = conn.createStatement(); String sql = "SELECT * FROM sample"; ResultSet rs = stmt.executeQuery(sql); while(rs.next()) < Blob blob = rs.getBlob("image"); byte [] bytes = blob.getBytes(1l, (int)blob.length()); for(int i=0; i> > >

Output

Connecting to a selected database. Connected database successfully. getting blob. [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103]

Answer by Julien Bryan

Does anyone have any idea to how to convert a db2 blob to character/string using java transformation.,Blob blob = rs.getBlob(cloumnName[i]);byte[] bdata = blob.getBytes(1, (int) blob.length());String s = new String(bdata);,First the «conversion» of a Binary port to a String port using a Java Transformation (JTX).,byte[] bdata = blob.getBytes(1, (int) blob.length());

Blob blob = rs . getBlob ( cloumnName [ i ]);
byte [] bdata = blob . getBytes ( 1 , ( int ) blob . length ());
String s = new String ( bdata );

Blob blob = rs.getBlob(cloumnName[i]);byte[] bdata = blob.getBytes(1, (int) blob.length());String s = new String(bdata);

Источник

[java] How to convert Blob to String and String to Blob in java

It is working fine but when I’m going to convert String to Blob and trying to insert into database then nothing inserting into database. I’ve used below code for converting String to Blob:

String value = (s); byte[] buff = value.getBytes(); Blob blob = new SerialBlob(buff); 

Can anyone help me about to converting of Blob to String and String to Blob in Java?

This question is related to java jdbc blob

The answer is

PreparedStatement ps1 = conn.prepareStatement("update t1 set a2=? where blob = conn.createBlob(); blob.setBytes(1, str.getBytes()); ps1.setBlob(1, blob); ps1.executeUpdate(); 

it may work even without BLOB, driver will transform types automatically:

 ps1.setBytes(1, str.getBytes); ps1.setString(1, str); 

Besides if you work with text CLOB seems to be a more natural col type

Use this to convert String to Blob. Where connection is the connection to db object.

 String strContent = s; byte[] byteConent = strContent.getBytes(); Blob blob = connection.createBlob();//Where connection is the connection to db object. blob.setBytes(1, byteContent); 

How are you setting blob to DB? You should do:

 //imagine u have a a prepared statement like: PreparedStatement ps = conn.prepareStatement("INSERT INTO table VALUES (?)"); String blobString= "This is the string u want to convert to Blob"; oracle.sql.BLOB myBlob = oracle.sql.BLOB.createTemporary(conn, false,oracle.sql.BLOB.DURATION_SESSION); byte[] buff = blobString.getBytes(); myBlob.putBytes(1,buff); ps.setBlob(1, myBlob); ps.executeUpdate(); 

To convert Blob to String in Java:

byte[] bytes = baos.toByteArray();//Convert into Byte array String blobString = new String(bytes);//Convert Byte Array into String 

And here is my solution, that always works for me

StringBuffer buf = new StringBuffer(); String temp; BufferedReader bufReader = new BufferedReader(new InputStreamReader(myBlob.getBinaryStream())); while ((temp=bufReader.readLine())!=null)

Источник

Читайте также:  Создание sql запросов python
Оцените статью