我正在使用以下代码在数据库中插入图像。它会存储两张图像,因为我使用了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