簡體   English   中英

Java-在JavaDB中將圖像存儲為Blob

[英]Java - Storing image as a Blob in JavaDB

我正在嘗試將圖像插入數據庫,但是得到以下信息:

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

    }
}

順便說一句,關於僅存儲圖像的路徑,問題是我希望用戶能夠向我發送圖像並將其存儲在文件中,並且我不確定如何確切地解決擁有多個圖像的問題。使用相同的名稱,重命名會是一個好的簡單解決方案嗎?

嘗試這個:

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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM