Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java JDBC binary parameters: cap bytes before binding a BLOB

Last updated: 5 Oct 20265 min read
tutorial
AdvancedBy AITrove Editorial

PreparedStatement.setBytes binds one byte array as a binary parameter. The application should bound that array before database I/O and keep the connection's transaction owner clear.

Operational contract

The method accepts a complete byte array no larger than 47,000 bytes, binds it to an INSERT, and requires one inserted row. The caller owns the array and Connection; this method does not mutate the array or commit. A driver may copy or buffer bytes internally, so the application cap does not describe total database-side memory. Do not share and mutate the array concurrently while executeUpdate is using it. For larger data, a stream API with explicit length, lifetime, and expanded-size policy is needed. A BLOB column and database limit must agree with this service cap.

Failure case

An intake receives 47,001 receipt bytes. The Java method rejects the payload before preparing a statement. A 47,000-byte payload can be bound, but database constraints may still reject it; the caller handles that SQLException and transaction rollback.

Java code

Java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Objects;

public class BoundedReceiptBlobInsert {
    public static void insert(Connection connection, long receiptId, byte[] document)
            throws SQLException {
        Objects.requireNonNull(document);
        if (document.length > 47_000)
            throw new IllegalArgumentException("Receipt document exceeds cap");
        try (PreparedStatement statement = connection.prepareStatement(
                "INSERT INTO receipt_documents (receipt_id, document_bytes) VALUES (?, ?)")) {
            statement.setLong(1, receiptId);
            statement.setBytes(2, document);
            if (statement.executeUpdate() != 1)
                throw new SQLException("Expected one receipt document insert");
        }
    }
}

Performance and ownership cost

The Java input already occupies O(B) bytes for B <= 47,000; driver buffering can add another O(B) or more. Database insert cost depends on transaction log, storage, and indexes. This bound protects intake memory but is not a total resource budget.

Common Mistakes

  • Do not accept unbounded byte arrays before binding.
  • Do not mutate a bound array from another thread during execution.
  • Do not assume the application byte cap replaces database column limits.

Connected lessons

java
parameter and row boundaries
jdbc-bounded-binary-parameter
Storage details