我正在使用以下代碼在數據庫中插入圖像。它會存儲兩張圖像,因爲我使用了PreparedStatement
和Statement
。使用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;
「請運行此代碼和腳本,您將在數據庫表中找到兩個圖像,但兩者都不同,我不知道爲什麼。」 - 抱歉,不值得努力。你應該在這裏做更多的工作。 – duffymo 2012-02-24 11:32:59
請正確縮進代碼,並在句子中使用正確的大寫。 – 2012-02-24 11:34:47
人們通常不會運行本站提供的代碼 - 風險太大。但他們會爲你查看你的代碼。你期望這兩個圖像是相同的嗎? – halfer 2012-02-24 11:37:30