Java文件上传到MySQL [英] Java File upload to MySQL

查看:501
本文介绍了Java文件上传到MySQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个问题从选择 JFileChooser 中获取 java.io.File 来上传 java.io.File 具有此表结构的MySQL表的对象

I have this problem getting a java.io.File from the selection of a JFileChooser to upload the said java.io.File object to the MySQL Table having this table structure

     COL_NAME  COL_TYPE     ATTRIBUTES        EXTRA
(PK) idSample  int(10)      UNSIGNED ZEROFILL AUTO_INCREMENT
     FileName  varchar(250)
     FileBin   blob         BINARY 

从这个Java代码中, newConnection 方法是该类的静态方法,其中它返回一个新实例一个DriverManager默认为上述MySQL数据库。另一件事,我使用 java.sql 包而不是 com.mysql.jdbc 包。

And from this Java code, the newConnection method is a static method of the class wherein it returns a new instance of a DriverManager default to the said MySQL Database. Another thing, I am using the java.sql package not the com.mysql.jdbc package.

public static boolean insert(final String filename, File file) throws SQLException, IOException {
    boolean flag = false;
    try {
        Connection connection = newConnection();
        PreparedStatement statement = connection.prepareStatement(SQL_INSERT);
        statement.setString(1, filename);
        statement.setBlob(2, new FileInputStream(file), file.length());
        flag = statement.executeUpdate() > 0;
        statement.close();
        connection.close();
    } catch (SQLException ex) {
        throw ex;
    } catch (IOException ex) {
        throw ex;
    }
    return flag;
}

当我尝试运行程序时,它会返回一个错误,导致 statement.setBlob 有这个堆栈跟踪的行:

When I tried to run the program, it returns an error leading to the statement.setBlob line having this stacktrace:

Exception in thread "main" java.lang.AbstractMethodError: com.mysql.jdbc.PreparedStatement.setBlob(ILjava/io/InputStream;J)V

如何解决此问题?

推荐答案

AbstractMethodError 表示你的JDBC驱动程序的 PreparedStatement s没有实现 setBlob(int,InputStream,long)

AbstractMethodError means your JDBC driver's PreparedStatements don't implement setBlob(int, InputStream, long).

使用旧的 setBlob(int,Blob)或更新你的驱动程序(Connector / J 5.1实现Jdbc 4.0,这应该是你的需要 setBlob(int,InputStream,long)

Use the older setBlob(int, Blob) or update your driver (Connector/J 5.1 implements Jdbc 4.0, which should be what you need for setBlob(int, InputStream, long))

这篇关于Java文件上传到MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆