Inserting BLOB Values with SQL INSERT Statements

This section describes how to insert BLOB values as normal strings using INSERT statements.

The simplest way to insert a binary string into a BLOB column is to use a SQL INSERT statement and include the binary string a SQL binary literal in the statement as shown in this sample program. Note that SQL binary literal format is 0x<hex_numbers>.

/* SqlServerBlobInsert.java
 * Copyright (c) HerongYang.com. All Rights Reserved.
 */
import java.sql.*;
public class SqlServerBlobInsert {
  public static void main(String [] args) {
    Connection con = null;
    try {
      com.microsoft.sqlserver.jdbc.SQLServerDataSource ds
        = new com.microsoft.sqlserver.jdbc.SQLServerDataSource();
      ds.setServerName("localhost");
//      ds.setPortNumber(60782);
      ds.setInstanceName("SQLEXPRESS");
      ds.setDatabaseName("AdventureWorks2019");
      ds.setUser("Herong");
      ds.setPassword("T0pSecret");
      con = ds.getConnection();

// Deleting the record for re-testing
      String subject = "Test on INSERT statement";
      Statement sta = con.createStatement();
      sta.executeUpdate("DELETE FROM Image WHERE Subject = '"
        +subject+"'");

// Inserting CLOB value with a regular insert statement
      sta = con.createStatement();
      int count = sta.executeUpdate(
        "INSERT INTO Image"
        +" (Subject, Body)"
        +" VALUES ('"+subject+"'"
        +", 0xC9CBBBCCCEB9C8CABCCCCEB9C9CBBB)"); //SQL Server format
//      +", x'C9CBBBCCCEB9C8CABCCCCEB9C9CBBB')"); // MySQL format

// Retrieving BLOB value with getBytes()
      ResultSet res = sta.executeQuery(
        "SELECT * FROM Image WHERE Subject = '"+subject+"'");
      res.next();
      System.out.println("The inserted record: ");
      System.out.println("   Subject = "+res.getString("Subject"));
      System.out.println("   Body = "
        +new String(res.getBytes("Body")));
      res.close();
      sta.close();

      con.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Compilation and execution of this program is below. The output confirms that the character string value was correctly inserted into the BLOB column:

herong> java -cp .;mssql-jdbc-9.4.1.jre16.jar SqlServerBlobInsert

The inserted record:
   Subject = Test on INSERT statement
   Body = ╔╦╗╠╬╣╚╩╝╠╬╣╔╦╗

Using SQL binary literals to insert BLOB values into database is simple. But it requires you to convert your binary data into the SQL binary literal format: 0x<hex_numbers>, which could be a problem if you have a very long binary data to enter.

Notice that the binary literal format on SQL Server is different than MySQL. This is another reason that you should avoid using binary literals in SQL statements to make your Java program portable.

Using PreparedStatement with setXXX() method is a much better choice.

Table of Contents

 About This Book

 JDBC (Java Database Connectivity) Introduction

 JDK (Java SE) Installation

 Microsoft SQL Server Express Edition

 Microsoft JDBC Driver for SQL Server

 Microsoft JDBC Driver - Query Statements and Result Sets

 Microsoft JDBC Driver - DatabaseMetaData Object

 Microsoft JDBC Driver - DDL Statements

 Microsoft JDBC Driver - DML Statements

 SQL Server - PreparedStatement

 SQL Server CLOB (Character Large Object) - TEXT

SQL Server BLOB (Binary Large Object) - BLOB

 Overview of BLOB (Binary Large Object)

 Create Tables with CLOB Columns

Inserting BLOB Values with SQL INSERT Statements

 Inserting BLOB Values with setBytes() Method

 Inserting BLOB Values with setBinaryStream() Method

 Closing InputStream Too Early on setBinaryStream()

 Retrieving BLOB Values with getBytes() Method

 Retrieving BLOB Values with getBinaryStream() Method

 Retrieving BLOB Values with getBlob() Method

 Inserting BLOB Values with setBlob() Method

 Using Connection Pool with JDBC

 JDBC-ODBC Bridge Driver - sun.jdbc.odbc.JdbcOdbcDriver

 JDBC-ODBC Bridge Driver - Flat Text Files

 JDBC-ODBC Bridge Driver - MS Access

 JDBC-ODBC Bridge Driver - MS SQL Server

 Archived Tutorials

 References

 Full Version in PDF/EPUB