Java PreparedStatement .setBinaryStream (int parameterIndex, InputStream x)

Syntax

PreparedStatement.setBinaryStream(int parameterIndex, InputStream x) has the following syntax.

void setBinaryStream(int parameterIndex,   InputStream x)   throws SQLException

Example

In the following code shows how to use PreparedStatement.setBinaryStream(int parameterIndex, InputStream x) method.


import java.awt.Image;
import java.awt.Toolkit;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
//from   w  w  w  .  ja v a  2 s .com
public class Main {
  public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    Statement st = conn.createStatement();

    st.executeUpdate("create table images (Id int, b BLOB);");

    File file = new File("myimage.gif");
    FileInputStream fis = new FileInputStream(file);
    PreparedStatement ps = conn.prepareStatement("insert into images values (?,?)");
    ps.setString(1, "10");
    ps.setBinaryStream(2, fis);
    ps.executeUpdate();
    
    
    
    ResultSet rset = st.executeQuery("select b from images");
    InputStream stream = rset.getBinaryStream(1);
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    int a1 = stream.read();
    while (a1 >= 0) {
      output.write((char) a1);
      a1 = stream.read();
    }
    Image myImage = Toolkit.getDefaultToolkit().createImage(output.toByteArray());
    output.close();
    
    
    ps.close();
    
    fis.close();
    st.close();
    conn.close();
  }
  private static Connection getConnection() throws Exception {
    Class.forName("org.hsqldb.jdbcDriver");
    String url = "jdbc:hsqldb:mem:data/tutorial";

    return DriverManager.getConnection(url, "sa", "");
  }
}




















Home »
  Java Tutorial »
    java.sql »




DatabaseMetaData
ParameterMetaData
PreparedStatement
ResultSet
Timestamp