2013-11-25 22 views
0

經過一天的搜索引擎優化後,我終於決定花時間詢問所有強大的SO社區。我正嘗試將圖像插入或更新到MySQL數據庫中。我正在使用的查詢和代碼如下:從Java插入/更新blob到MySQL

FileInputStream inputStream = new FileInputStream(file); 

    String[] str_array = file.getName().split("-"); 
    String stringb = str_array[1]; 
    String stringc = str_array[2]; 
    String fingerName = stringc.substring(0, 2); 
    //gets file name and splits it accordingly 

    String id = getID.id(stringb); //does a sql lookup to get the previously inserted id according to the stringb(users unique id number) 

    String INSERT_PIC = "INSERT INTO database.user_picture(id_ref, picture_num, user_image) values('" + id + "', ?, ?) ON DUPLICATE KEY UPDATE user_image = ?;"; 

    //creates the sql statement that inserts or updates according to the primary keys id_ref and picture_num 

    ps = (PreparedStatement) connection.prepareStatement(INSERT_PIC); 

    ps.setString(1, fingerName); 
    ps.setBinaryStream(2, (InputStream) inputStream, file.length()); 
    ps.setBinaryStream(3, (InputStream) inputStream, file.length()); 

    //creates the prepared statement and inserts the 3 parameters 

    ps.executeUpdate(); 
    connection.commit(); 
    //executes the query on the connected database 

我很確定這會起作用。測試時,它會正確地將圖像插入到數據庫中。更新所有字段時更新正確,除了blob/image字段改爲NULL。

我不知道爲什麼發生這種情況或任何其他方式來得到這個工作,任何建議,將不勝感激......

回答

1

您正在爲參數2和3提供相同的輸入流。 執行語句時,首先讀取參數2流直到結束。 當JDBC驅動程序嘗試讀取參數3的流時,它已經在它的末尾,因爲它是同一個流實例。

儘量提供兩個輸入流:

FileInputStream inputStream1 = new FileInputStream(file); 
FileInputStream inputStream2 = new FileInputStream(file); 
[...] 
ps.setBinaryStream(2, (InputStream) inputStream1, file.length()); 
ps.setBinaryStream(3, (InputStream) inputStream2, file.length()); 

另外,不要忘記關閉流在一些finally塊。

祝你好運。

+0

兩個不同的輸入流會同時讀取同一文件是否會導致異常?從邏輯上講,我認爲這可能會導致類似於線程死鎖的情況 – DeanMWake

+0

只要它們都只讀,它不應該引起任何問題。 – hendrik

1

我的猜測是第一的setBinaryStream()消耗流。所以第二次調用setBinaryStream()只是讀取「null」。