Inserting BLOB Values with setBlob Method

From Java Example Source Code

Jump to: navigation, search

Contents

[edit] Overview - Inserting BLOB Values with setBlob Method

This Java example program shows how to insert BLOB Values with setBlob Method.

[edit] Java Source Code

  • Package: example.jdbc.preparedstatement
  • File: DemoPreparedStatementSetBlob.java
package example.jdbc.preparedstatement;
 
/*
 * 
 * Defining the Table: Oracle and MySql
 * 
 * create table MyPictures ( id INT PRIMARY KEY, name VARCHAR(0), photo BLOB );
 */
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
 
public class DemoPreparedStatementSetBlob {
    public static Connection getConnection() throws Exception {
	String driver = "org.gjt.mm.mysql.Driver";
	String url = "jdbc:mysql://localhost/databaseName";
	String username = "root";
	String password = "root";
	Class.forName(driver);
	Connection conn = DriverManager.getConnection(url, username, password);
	return conn;
    }
 
    public static void main(String[] args) throws Exception {
	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	java.sql.Blob blob = null;
	try {
	    conn = getConnection();
	    // prepare blob object from an existing binary column
	    pstmt = conn.prepareStatement("select photo from my_pictures where id = ?");
	    pstmt.setString(1, "0001");
	    rs = pstmt.executeQuery();
	    rs.next();
	    blob = rs.getBlob(1);
 
	    // prepare SQL query for inserting a new row using setBlob()
	    String query = "insert into blob_table(id, blob_column) values(?, ?)";
	    // begin transaction
	    conn.setAutoCommit(false);
 
	    pstmt = conn.prepareStatement(query);
	    pstmt.setString(1, "0002");
	    pstmt.setBlob(2, blob);
 
	    int rowCount = pstmt.executeUpdate();
	    System.out.println("rowCount=" + rowCount);
	    // end transaction
	    conn.commit();
	} finally {
	    rs.close();
	    pstmt.close();
	    conn.close();
	}
    }
}

[edit] What Result You Can Get

Coming soon...

[edit] Required External Libraries and/or Files for this Java Example

In order to run this Java example, one of the following libraries may be required: In order to run this example program, one of the following libraries may be required:


[edit] How to Run this Java Example Program

We recommend running this Java example program with Eclipse.

For assistance in working with Eclipse, please see How to Run Java Program with Eclipse.

It's fairly easy.



[edit] Question & Answer

Any question?

Click edit and post your question or answer here.


Personal tools