/*
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();
}
}
}
|