使用PreparedStatement在Java中插入blob数据 [英] Inserting blob data in Java using PreparedStatement
本文介绍了使用PreparedStatement在Java中插入blob数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用以下代码在数据库中插入图像。它将存储两个图像,因为我使用了 PreparedStatement
和 Statement
。
I am using the following code to insert an image in a database. It will store two images because I have used PreparedStatement
and Statement
.
当我运行此代码时,我在数据库中获得了两个图像。但这两个图像是不同的,我不明白为什么。使用 PreparedStatement
,它完全插入。当我使用 Statement
时,我希望拥有相同的图像。为什么它现在不工作,我怎么能让它工作?
When I run this code, I get two images in the database. But the two images are different, and I don't understand why. Using PreparedStatement
, it is inserting perfectly. I want to have the same image when I use Statement
. Why is it not working now, and how can I make it work?
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;
推荐答案
将setBlob与InputStream一起使用
Use setBlob with 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);
这篇关于使用PreparedStatement在Java中插入blob数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文