Estoy usando el siguiente código para insertar una imagen en una base de datos. Almacenará dos imágenes porque he usado PreparedStatement
y Statement
.Insertar datos de blob en Java utilizando PreparedStatement
Cuando ejecuto este código, obtengo dos imágenes en la base de datos. Pero las dos imágenes son diferentes, y no entiendo por qué. Usando PreparedStatement
, se está insertando perfectamente. Quiero tener la misma imagen cuando uso Statement
. ¿Por qué no funciona ahora y cómo puedo hacerlo funcionar?
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;
"por favor, ejecute este código y el script encontrará dos imágenes en la tabla de la base de datos, pero ambas son diferentes, no sé por qué". - lo siento, no vale la pena el esfuerzo. Deberías estar haciendo más trabajo aquí. – duffymo
Por favor, escriba su código apropiadamente y use mayúsculas en sus oraciones. –
Generalmente, la gente no ejecutará el código proporcionado en este sitio, demasiado arriesgado. Pero revisarán tu código por ti. ¿Esperas que las dos imágenes sean iguales? – halfer