2

我正在尝试将图像插入数据库,但得到以下信息:

java.sql.SQLDataException:试图从“java.io.InputStream(ASCII)”类型的数据值中获取“BLOB”类型的数据值。

我在数据库中使用 blob。

这是我进行插入的方式:

package javaapplication16;
import com.sun.rowset.CachedRowSetImpl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sql.rowset.CachedRowSet;

public class JavaApplication16 {

    public static void main(String[] args) throws FileNotFoundException {
        try {
            String driver = "org.apache.derby.jdbc.EmbeddedDriver";
            try {
                try {
                    Class.forName(driver).newInstance();
                } catch (InstantiationException ex) {
                    Logger.getLogger(JavaApplication16.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IllegalAccessException ex) {
                    Logger.getLogger(JavaApplication16.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(JavaApplication16.class.getName()).log(Level.SEVERE, null, ex);
            }

            CachedRowSet crs = null;
            crs = new CachedRowSetImpl();
            crs.setUrl("jdbc:derby:derbyDB; create = true");
            crs.setUsername("x");
            crs.setPassword("x");
            crs.setCommand("drop table tbl");
            crs.execute();
            crs.setCommand("CREATE TABLE tbl (ID blob)");
            crs.execute();
            File f = new File("/images/exam_gif_to_png.gif");
            crs.setCommand("insert into tbl (id) values (?)");
            FileInputStream fin = new FileInputStream(f);
            crs.setBinaryStream(1, fin, (int) f.length());
            crs.execute();
        } catch (SQLException ex) {
            Logger.getLogger(JavaApplication16.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

顺便说一句,关于仅存储图像的路径,问题是我希望用户能够向我发送图像并将它们存储在一个文件中,我不确定如何准确解决拥有多个图像的问题使用相同的名称,重命名会是一个好的简单的解决方案吗?

4

1 回答 1

0

尝试这个:

File f = new File(imagePath);
FileInputStream fin = new FileInputStream(f);
crs.setBinaryStream(5, fin, (int) f.length());

编辑---编辑

尝试这个:

我认为您的问题是您没有传播更改。

acceptChanges()在每个命令后调用。

crs.setCommand("drop table tbl");
crs.execute();
crs.acceptChanges();

crs.setCommand("CREATE TABLE tbl (ID blob)");
crs.execute();
crs.acceptChanges();

crs.setBinaryStream(1, fin, (int) f.length());
crs.execute();
crs.acceptChanges();
于 2013-04-23T20:33:25.510 回答