使用PreparedStatement在Java中插入blob数据

我使用以下代码在数据库中插入图像。 它将存储两个图像,因为我使用了PreparedStatementStatement

当我运行此代码时,我在数据库中获得两个图像。 但这两个图像是不同的,我不明白为什么。 使用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; 

当然他们会有所不同。 以下查询执行以下操作:

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

取b1,这是一个字节数组,并调用它的toString()方法。 这会产生类似[B @ 8976876的字符串,这意味着“具有hashCode 8976876的字节数组类型的对象”,但根本不代表字节数组的内容。 然后在表中插入此字符串。

字节数组不是String。 故事结局。 必须使用预准备语句在表中插入二进制数据。 实际上,您应该始终使用预准备语句来执行具有非常量参数的任何查询。

将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); 

您的问题是您将字符串与字节数组连接(在您对executeStatment的调用中)

有关如何使用语句插入blob,请参阅此答案: https : //stackoverflow.com/a/2609614/355499