我使用以下代码在数据库中插入图像.它将存储两个图像,因为我使用过PreparedStatement和Statement.
当我运行此代码时,我在数据库中获得两个图像.但这两个图像是不同的,我不明白为什么.使用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();
}
}
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
JB *_*zet 10
当然他们会有所不同.以下查询执行以下操作:
"insert into registration(image) values('"+b1+"')"
Run Code Online (Sandbox Code Playgroud)
取b1,这是一个字节数组,并调用它的toString()方法.这会导致像[B @ 8976876这样的字符串,这意味着"具有hashCode 8976876的字节数组类型的对象",但根本不代表字节数组的内容.然后在表中插入此字符串.
字节数组不是String.故事结局.您必须使用准备好的语句在表中插入二进制数据.实际上,您应该始终使用预准备语句来执行具有非常量参数的任何查询.
Ren*_*Ren 10
将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);
Run Code Online (Sandbox Code Playgroud)