Sto usando il seguente codice per inserire un'immagine in un database. Memorerà due immagini perché ho usato PreparedStatement
e Statement
.Inserimento dei dati BLOB in Java con PreparedStatement
Quando si esegue questo codice, ottengo due immagini nel database. Ma le due immagini sono diverse e non capisco perché. Usando PreparedStatement
, si sta inserendo perfettamente. Voglio avere la stessa immagine quando uso Statement
. Perché non funziona ora e come posso farlo funzionare?
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;
"esegui questo codice e script troverai due immagini nella tabella del database, ma entrambe sono diverse non so perché." - scusa, non ne vale la pena. Dovresti fare più lavoro qui. – duffymo
Si prega di indentare il codice in modo corretto e utilizzare le maiuscole nelle frasi. –
In genere, le persone non eseguono il codice fornito su questo sito: troppo rischioso. Ma controlleranno il tuo codice per te. Ti aspetti che le due immagini siano le stesse? – halfer