2012-02-24 76 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); 
相关问题