pinto
pinto

Reputation: 127

Insert images into the database

Image insertion into database showing error. This is the code I have tried

package com.mysql.db.examples;

import java.io.*;
import java.sql.*;

 public class BlobInsertTest {

    public static void main(String a[]){

    Connection con = null;
    PreparedStatement ps = null;
    InputStream is = null;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.
                getConnection("jdbc:mysql://localhost:3306/STUDENT_DB","root","sys");
        ps = con.prepareStatement("insert into STUDENT_PROFILE values (?,?)");
        ps.setInt(1, 101);
        is = new FileInputStream(new File("D:\\supriyo_pic.JPG"));
        ps.setBinaryStream(2, is);
        ps.executeUpdate();

    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally{
        try{
            if(is != null) is.close();
            if(ps != null) ps.close();
            if(con != null) con.close();
        } catch(Exception ex){}
    }
 }
}

Its showing:

Exception in thread "main" java.lang.AbstractMethodError: 
  com.mysql.jdbc.ServerPreparedStatement.setBinaryStream(ILjava/io/InputStream;)V 
  at com.mysql.db.examples.BlobInsertTest.main(BlobInsertTest.java:26)

Upvotes: 0

Views: 949

Answers (1)

Marcel Stör
Marcel Stör

Reputation: 23525

Depending on the version of your MySQL JDBC driver (is it a JDBC 3 or 4 type?) you need to set different parameters for the setBinaryStream method.

Detailed info can be found here: http://www.herongyang.com/JDBC/MySQL-BLOB-setBinaryStream.html

So, you should test with this:

...
File file = new File("D:\\supriyo_pic.JPG");
is = new FileInputStream(file);
ps.setBinaryStream(2, is, (int)file.length());
...

Upvotes: 1

Related Questions