Table of Contents
Storing Blobs to the Database
Retrieve blobs from the database
Example
Output
Home Database Mysql Tutorial What is the JDBC Blob data type? How to store and read the data in it?

What is the JDBC Blob data type? How to store and read the data in it?

Sep 14, 2023 pm 06:57 PM

什么是 JDBC Blob 数据类型?如何存储和读取其中的数据?

BLOB is a binary large object that can hold a variable amount of data with a maximum length of 65535 characters.

They are used to store large amounts of binary data, such as images or other types of data. document. Fields defined as TEXT also hold large amounts of data. The difference between the two is that sorting and comparisons of stored data are case-sensitive in BLOBs but not case-sensitive in TEXT fields. You did not specify the length using BLOB or TEXT.

Storing Blobs to the Database

To store the Blob data type to the database, follow these steps using a JDBC program

Step 1: Connect to the database

You can connect to the database using the DriverManagergetConnection() method

by passing the MySQL URL (jdbc:mysql://localhost /sampleDB) (where exampleDB is the database name), username and password as parameters to the getConnection() method.

String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
Copy after login

Step 2: Create a prepared statement

Use the prepareStatement() method of the Connection interface to create a PreparedStatement object. Pass the insertion query (with placeholders) as a parameter to this method.

PreparedStatement pstmt = con.prepareStatement("INSERT INTO MyTableVALUES(?, ?)");
Copy after login

Step 3: Set the value for the placeholder

Use the setter method of the PreparedStatement interface to set the value to the placeholder. Select the method based on the data type of the column. For example, if the column is of type VARCHAR, use the setString() method; if the column is of type INT, you can use the setInt() method.

If the column is of type Blob, you can set its value using the setBinaryStream() or setBlob() method. These methods are passed an integer variable representing the parameter index and an object of the InputStream class as parameters.

pstmt.setString(1, "sample image");
//Inserting Blob type
InputStream in = new FileInputStream("E:\images\cat.jpg");
pstmt.setBlob(2, in);
Copy after login

Step 4: Execute the statement

Use the execute() method of the PreparedStatement interface to execute the PreparedStatement created above object.

Retrieve blobs from the database

The getBlob() method of the ResultSet interface accepts an integer representing the index of the column (or a string value representing the column name), and retrieves the value of the specified column , and returned as a Blob object. The

getBytes()

method of the

while(rs.next()) {
   rs.getString("Name");
   rs.getString("Type");
   Blob blob = rs.getBlob("Logo");
}
Copy after login
Blob interface retrieves the contents of the current Blob object and returns it as a byte array.

Using the getBlob() method, you can get the contents of the blob into a byte array and create the image using the write() method FileOutputStream Object.

byte byteArray[] = blob.getBytes(1,(int)blob.length());
FileOutputStream outPutStream = new FileOutputStream("path");
outPutStream.write(byteArray);
Copy after login

Example

The following example creates a table of blob data type in a MySQL database and inserts an image into it. Retrieve and store it in the local file system.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class BlobExample {
   public static void main(String args[]) throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating a table
      Statement stmt = con.createStatement();
      stmt.execute("CREATE TABLE SampleTable( Name VARCHAR(255), Image BLOB)");
      System.out.println("Table Created");
      //Inserting values
      String query = "INSERT INTO SampleTable(Name,image) VALUES (?, ?)";
      PreparedStatement pstmt = con.prepareStatement(query);
      pstmt.setString(1, "sample image");
      FileInputStream fin = new FileInputStream("E:\images\cat.jpg");
      pstmt.setBlob(2, fin);
      pstmt.execute();
      //Retrieving the data
      ResultSet rs = stmt.executeQuery("select * from SampleTable");
      int i = 1;
      System.out.println("Contents of the table are: ");
      while(rs.next()) {
         System.out.println(rs.getString("Name"));
         Blob blob = rs.getBlob("Image");
         byte byteArray[] = blob.getBytes(1,(int)blob.length());
         FileOutputStream outPutStream = new
         FileOutputStream("E:\images\blob_output"+i+".jpg");
         outPutStream.write(byteArray);
         System.out.println("E:\images\blob_output"+i+".jpg");
         System.out.println();
         i++;
      }
   }
}
Copy after login

Output

Connection established......
Table Created
Contents of the table are:
sample image
E:\images\blob_output1.jpg
Copy after login

The above is the detailed content of What is the JDBC Blob data type? How to store and read the data in it?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do you alter a table in MySQL using the ALTER TABLE statement? How do you alter a table in MySQL using the ALTER TABLE statement? Mar 19, 2025 pm 03:51 PM

The article discusses using MySQL's ALTER TABLE statement to modify tables, including adding/dropping columns, renaming tables/columns, and changing column data types.

How do I configure SSL/TLS encryption for MySQL connections? How do I configure SSL/TLS encryption for MySQL connections? Mar 18, 2025 pm 12:01 PM

Article discusses configuring SSL/TLS encryption for MySQL, including certificate generation and verification. Main issue is using self-signed certificates' security implications.[Character count: 159]

What are some popular MySQL GUI tools (e.g., MySQL Workbench, phpMyAdmin)? What are some popular MySQL GUI tools (e.g., MySQL Workbench, phpMyAdmin)? Mar 21, 2025 pm 06:28 PM

Article discusses popular MySQL GUI tools like MySQL Workbench and phpMyAdmin, comparing their features and suitability for beginners and advanced users.[159 characters]

How do you handle large datasets in MySQL? How do you handle large datasets in MySQL? Mar 21, 2025 pm 12:15 PM

Article discusses strategies for handling large datasets in MySQL, including partitioning, sharding, indexing, and query optimization.

Explain InnoDB Full-Text Search capabilities. Explain InnoDB Full-Text Search capabilities. Apr 02, 2025 pm 06:09 PM

InnoDB's full-text search capabilities are very powerful, which can significantly improve database query efficiency and ability to process large amounts of text data. 1) InnoDB implements full-text search through inverted indexing, supporting basic and advanced search queries. 2) Use MATCH and AGAINST keywords to search, support Boolean mode and phrase search. 3) Optimization methods include using word segmentation technology, periodic rebuilding of indexes and adjusting cache size to improve performance and accuracy.

How do you drop a table in MySQL using the DROP TABLE statement? How do you drop a table in MySQL using the DROP TABLE statement? Mar 19, 2025 pm 03:52 PM

The article discusses dropping tables in MySQL using the DROP TABLE statement, emphasizing precautions and risks. It highlights that the action is irreversible without backups, detailing recovery methods and potential production environment hazards.

How do you represent relationships using foreign keys? How do you represent relationships using foreign keys? Mar 19, 2025 pm 03:48 PM

Article discusses using foreign keys to represent relationships in databases, focusing on best practices, data integrity, and common pitfalls to avoid.

How do you create indexes on JSON columns? How do you create indexes on JSON columns? Mar 21, 2025 pm 12:13 PM

The article discusses creating indexes on JSON columns in various databases like PostgreSQL, MySQL, and MongoDB to enhance query performance. It explains the syntax and benefits of indexing specific JSON paths, and lists supported database systems.

See all articles