2012-02-24 40 views
6

我正在使用以下代碼在數據庫中插入圖像。它會存儲兩張圖像,因爲我使用了PreparedStatementStatement使用PreparedStatement在Java中插入Blob數據

當我運行此代碼時,我在數據庫中得到兩個圖像。但是這兩個圖像是不同的,我不明白爲什麼。使用PreparedStatement,它插入完美。我想在使用Statement時擁有相同的圖像。爲什麼現在不工作,我該如何使它工作?

import java.io.*; 
import java.sql.*; 
public class Image 
{ 
    public static void main(String args[]) throws Exception 
    { 
     System.out.println("kshitij"); 
     Class.forName("com.mysql.jdbc.Driver"); 
     Connection cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/jsfdb","root","kshitij"); 
     Statement st=cn.createStatement(); 
     File f1=new File("c:\\k1.jpg"); 
     FileInputStream fin=new FileInputStream(f1); 
     //DataInputStream dataIs = new DataInputStream(new FileInputStream(f1)); 
     PreparedStatement pst = cn.prepareStatement("insert into registration(image) values(?)"); 
     //pst.setInt(1,67); 
     pst.setBinaryStream(1,fin,fin.available()); 
     pst.executeUpdate(); 
     //int length=(int)f1.length(); 
     byte [] b1=new byte[(int)f1.length()]; 
     fin.read(b1); 
     fin.close(); 
     st.executeUpdate("insert into registration(image) values('"+b1+"')"); 
     System.out.println("Quesry Executed Successfully"); 
     FileOutputStream fout=new FileOutputStream("d://k1.jpg"); 
     fout.write(b1); 
     fout.close(); 
    } 
} 

MySQL的

CREATE DATABASE IF NOT EXISTS jsfdb; 
USE jsfdb; 

-- Definition of table `registration` 
DROP TABLE IF EXISTS `registration`; 
CREATE TABLE `registration` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 
    `image` blob NOT NULL, 
    PRIMARY KEY (`id`) 
) ENGINE=InnoDB AUTO_INCREMENT=234 DEFAULT CHARSET=latin1; 
+3

「請運行此代碼和腳本,您將在數據庫表中找到兩個圖像,但兩者都不同,我不知道爲什麼。」 - 抱歉,不值得努力。你應該在這裏做更多的工作。 – duffymo 2012-02-24 11:32:59

+0

請正確縮進代碼,並在句子中使用正確的大寫。 – 2012-02-24 11:34:47

+0

人們通常不會運行本站提供的代碼 - 風險太大。但他們會爲你查看你的代碼。你期望這兩個圖像是相同的嗎? – halfer 2012-02-24 11:37:30

回答

9

他們當然會有所不同。下面的查詢做以下的事情:

"insert into registration(image) values('"+b1+"')" 

採取B1,它是一個字節數組,並調用其toString()方法。這會產生像[B @ 8976876這樣的字符串,這意味着「一個帶有hashCode 8976876的字節數組類型的對象」,但根本不代表字節數組的內容。然後將該字符串插入表中。

一個字節數組不是一個字符串。故事結局。您需要必須使用準備好的語句在表中插入二進制數據。實際上,您應該始終使用預處理語句來執行任何具有非常量參數的查詢。

+0

那是「不正確」?在您的答案中,您將二進制數據轉換爲字符串。所以你不再插入二進制數據,而是一個String。通過這樣做,你可以節省時間(編碼和解碼)和空間(因爲base64字符串需要4個字節來表示3個二進制字節)。 – 2012-12-13 07:57:31

+0

要插入二進制數據,是的,這是真的。無論如何,準備好的陳述總的來說是一個很好的做法。 – 2012-12-13 10:24:34

8

使用的setBlob與InputStream

File file= new File("your_path"); 
FileInputStream inputStream= new FileInputStream(file); 

PreparedStatement statement = connection.prepareStatement("INSERT INTO yourTable (yourBlob) VALUES (?)"); 
statement.setBlob(1, inputStream); 
相關問題