将图像插入数据库

时间:2013-11-27 20:58:54

标签: java jdbc

图像插入数据库显示错误。这是我试过的代码

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){}
    }
 }
}

显示:

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)

1 个答案:

答案 0 :(得分:1)

根据MySQL JDBC驱动程序的版本(是JDBC 3还是4类型?),您需要为setBinaryStream方法设置不同的参数。

详细信息可在此处找到:http://www.herongyang.com/JDBC/MySQL-BLOB-setBinaryStream.html

所以,你应该测试一下:

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