I'am getting a problem whene i execute upadate query , the problem is whene i wante to update the blob column im my sqlite table, i notice that only the path this blob file are stored. but whene is use insert query with binding value like that :pst.setBinaryStream(File); it works fine!
I get my blob file with this code :
File image=null;
URL photoURL = null;
try {
photoURL = new URL(addadh_adherent_photo_label.getText());
} catch (MalformedURLException ex) {
Logger.getLogger(ParametresController.class.getName()).log(Level.SEVERE, null, ex);
}
try {
image= new File( URLDecoder.decode( photoURL.getFile(), "UTF-8" ) );
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(ParametresController.class.getName()).log(Level.SEVERE, null, ex);
}
FileInputStream fis = null;
try {
fis = new FileInputStream(image);
} catch (FileNotFoundException ex) {
Logger.getLogger(ParametresController.class.getName()).log(Level.SEVERE, null, ex);
}
and here is my update query :
int AderentId =100;
String updateAderent=" UPDATE gss_aderent SET"
+ "ad_photo='"+image+"'
+ "WHERE ad_id='"+AderentId+"' ";
stmt.executeUpdate(updateAderent);
My problem is : The updated value isn't a blob value but just his path:( my question is how to store(update) blob value in update query ? does exist a method to bind BinaryStream parametre for update query ? can i use preparedStatement in update query ?
Your application looks like it's open to SQL Injection attacks
Use a PreparedStatement and setBlob(int x, InputStream in)
Related
I am trying to convert a byte array to a bufferedImage to display in a jLabel but the ImageIO.read() property is returning a null value and therefore a NullPonterException. What should I do?
InputStream input = new ByteArrayInputStream(array);
try {
BufferedImage bufer = ImageIO.read(input);
ImageIcon icon=new ImageIcon(new ImageIcon(bufer).getImage().getScaledInstance(jLabel3.getWidth(), jLabel3.getHeight(), Image.SCALE_SMOOTH));
jLabel3.setIcon(icon);
} catch (IOException ex) {
Logger.getLogger(Add.class.getName()).log(Level.SEVERE, null, ex);
}`
According to the javadoc, the read(InputStream) method ...
"Returns a BufferedImage as the result of decoding a supplied InputStream with an ImageReader chosen automatically from among those currently registered. The InputStream is wrapped in an ImageInputStream. If no registered ImageReader claims to be able to read the resulting stream, null is returned."
It is most likely that the last sentence explains your problem.
What should I do?
So your approach to solving this would be:
Check that the contents of array is what you expect it to be.
Determine what kind of image format it is, and that it is correctly represented. For example, if the image was stored in a database or sent in a network request, make sure that it hasn't gotten mangled in the process.
Check that it is a supported image format; i.e. one that there should be a registered ImageReader class for.
Thanks for helping me to solve the problem I going to post the response here to help other.
1.The queries to the database (postgresql) must be preparedStatement because if you are saving an image converted to byte [] this declaration gives you a setBinaryStream functionality and when you retrieve it and add it in a byte[] nothing changes
////This way save the image and his path (the last is optional)
JFileChooser f = new JFileChooser();
f.showOpenDialog(null);
File file = f.getSelectedFile();
FileInputStream s = null;
String path = file.getAbsolutePath();
try {
s = new FileInputStream(file);
Conexion();
PreparedStatement pq = conexion.prepareStatement("INSERT INTO prueba(foto, cam) VALUES (?, ?);");
pq.setBinaryStream(1, s, (int) file.length());
pq.setString(2, path);
pq.executeUpdate();
s.close();
} catch (ClassNotFoundException ex) {
Logger.getLogger(Add.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Add.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Add.class.getName()).log(Level.SEVERE, null, ex);
}
/////This way retrive the info
byte[] array = null;
String photopath = "";
try {
Conexion();
PreparedStatement p = conexion.prepareStatement("SELECT foto, cam FROM prueba;");
ResultSet sq = p.executeQuery();
while (sq.next()) {
array = sq.getBytes("foto");
photopath = sq.getString("cam");
//jLabel3.setIcon(new ImageIcon(array));
break;
}
sq.close();
p.close();
} catch (ClassNotFoundException ex) {
Logger.getLogger(Add.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Add.class.getName()).log(Level.SEVERE, null, ex);
}
ImageIcon icon=new ImageIcon(array);
I have a table named images in SQL with 3 columns, imageID, username and image. I am trying to get all of the pictures of a particular user into a single array but for some reason it is not working properly. I don't know what I am doing wrong. The images go into the listOfImages array and the name of the images go into the imageName array:
ArrayList<BufferedImage> listOfImages = new ArrayList<BufferedImage>();
ArrayList<String> imageName = new ArrayList<String>();
try {
myConn = connection
String sql = "SELECT * FROM images WHERE username=?";
PreparedStatement statement = myConn.prepareStatement(sql);
statement.setString(1, username);
ResultSet result = statement.executeQuery();
while (result.next()) {
String getImageName = result.getString("imageID");
Blob blob = result.getBlob("image");
listOfImages.add(javax.imageio.ImageIO.read(blob.getBinaryStream()));
imageName.add(getImageName);
}
myConn.close();
} catch (SQLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
System.out.println(imageName);
Error Messages:
Stack trace:Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
listOfImages.add( javax.imageio.ImageIO.read( blob.getBinaryStream() ) );
The issue is that I was incorrectly converting a blob to a buffered image. What is the correct way to do it?
solved: I had null values for the blob entry inside the SQL database. When reading it the error was caused.
I'm trying to insert BLob into Oracle database using vert.x, i get the upload File
for (FileUpload f : routingContext.fileUploads()){
System.out.println("file name " + f.fileName());
System.out.println("size name " + f.size());
System.out.println("Uploaded File " + f.uploadedFileName());
}
I have converted FileUpload to bytes Array by using :
Buffer fileUploaded = routingContext.vertx().fileSystem().readFileBlocking(f.uploadedFileName());
byte[] fileUploadedBytes = fileUploaded.getBytes();
Now I want to insert it directly to the Oracle database, i have tried to use updateWithParams, but i don't know how to add Blob into the query params.
thank you for your help
this is my implementation to resolve my problem , now I can insert file Blob into the Oracle dataBase, I hope that will help someone in the future.
ByteArrayInputStream finalBis = bis;
byte[] finalFileUploadedBytes = fileUploadedBytes;
DB.getConnection(connection -> {
if (connection.succeeded()) {
CallableStatement stmt = null;
try {
stmt = connection.result().getConnection().prepareCall(SQL.INSERT_DOCS_QUERY);
stmt.setBinaryStream(1, finalBis, finalFileUploadedBytes.length);
stmt.setString(2,desiDoc);
stmt.setString(3,sourDoc);
logger.debug(stmt);
stmt.execute();
finalBis.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("nooot ok");
}
});
I am retrieving gif images from Wolfram|Alpha. In an effort to minimize queries I want to store those images and only query W|A when the data is changed, so I am storing the images as a bytea data type in my postgres db. The "save" portion seems to be working because there is data. System.out.println(rs.getString("fnPlotImg")) yields this: \x4275666665726564496d6167654035356437373834323a2074797065203d203120446972656374436f6c6f724d6f64656c3a20726d61736b3d66663030303020676d61736b3d6666303020626d61736b3d666620616d61736b3d3020496e7465676572496e7465726c65617665645261737465723a207769647468203d2032303020686569676874203d20313335202342616e6473203d203320784f6666203d203020794f6666203d203020646174614f66667365745b305d2030
I have been able to successfully update the image from W|A using this bit of code:
String path = ((WAImage) element).getURL();
URL url = new URL(path);
BufferedImage image = ImageIO.read(url);
picLabel.setIcon(new ImageIcon(image));
I would like to update my application with the image from the database and have attempted this code:
byte[] ba = rs.getBytes("fnPlotImg");
try{
picLabel.setIcon(new ImageIcon(ba));
} catch (NullPointerException e) {
e.printStackTrace();
}
My rationale is that bytea is a byte array, getBytes() is supposed to retrieve a byte array, and ImageIcon() is supposed to handle a byte array.However, if I don't build in a null pointer exception it errors out. I presume this is because I am not saving the image to DB correctly or I am not retrieving it correctly.
All thoughts are welcome, I'm getting fatigued so I'll check in the morning with fresh eyes.
I don't have a installation of PostgreSQL available, but I think you should be writing/reading the image format and not the BufferedImage data.
For example, writing might look something like...
Connection con = ...;
BufferedImage img = ...;
try (PreparedStatement stmt = con.prepareStatement("insert into tableofimages (image) values (?)")) {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
ImageIO.write(img, "png", baos);
try (ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray())) {
stmt.setBinaryStream(1, bais);
int rows = stmt.executeUpdate();
System.out.println(rows + " rows updated");
}
}
} catch (SQLException | IOException exp) {
exp.printStackTrace();
}
And reading might look something like...
Connection con = ...;
try (PreparedStatement stmt = con.prepareStatement("select image from tableofimages")) {
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
try (InputStream is = rs.getBinaryStream(1)) {
BufferedImage img = ImageIO.read(is);
}
}
}
} catch (SQLException | IOException exp) {
exp.printStackTrace();
}
I'm trying to store a text file in a MySQL database, and when needed, save it to a file.
To save the file, I do:
public void saveFile_InDB(File file)
{
try {
String sql = "INSERT INTO sent_emails (fileName, time, clientName) values (?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, new Date().toString());
statement.setString(2, new Date().toString());
InputStream inputStream = new FileInputStream(file);
statement.setBinaryStream(3, inputStream);
int row = statement.executeUpdate();
if (row > 0) {
System.out.println("File saved sucessfully.");
}
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
And to retreive and save the file:
public void retrieveFile_fromDB()
{
try {
Statement stmt = (Statement) conn.createStatement();
ResultSet res = stmt.executeQuery("SELECT * FROM sent_emails WHERE clientName='sally'");
FileOutputStream fos = new FileOutputStream("file.txt");
if (res.next()) {
Blob File = (Blob) res.getBlob("fileName");
InputStream is = File.getBinaryStream();
int b = 0;
while ((b = is.read()) != -1) {
fos.write(b);
}
fos.flush();
}
} catch (IOException e) {
e.getMessage (); e.printStackTrace();
System.out.println(e);
} catch (SQLException e) {
e.getMessage (); e.printStackTrace();
System.out.println(e);
}
}
Storing the file works, but when I try to retrieve and save it, nothing is stored in the output file?
if you want read file from db Mysql
change this part in your code
Blob File = (Blob) res.getBlob("fileName");
InputStream is = File.getBinaryStream();
int b = 0;
while ((b = is.read()) != -1) {
fos.write(b);
}
fos.flush();
use this code read array of bytes
byte [] bs=res.getBytes("fileName");
fos.write(bs);
it will work
if you return multiple files from db you must declare
FileOutputStream fos = new FileOutputStream("file.txt");
inside while loop and change name of file to avoid overriding
You do not seem to put into the database the things that the column names describe?
fileName and time are for example both set to a timestamp, and clientName is set to the contents of the file. When you later try to select based on clientName, you are actually selecting based on the contents of the file.
Furthermore, when reading the data, you are reading the blob data from the column fileName, but this is wrong because:
fileName contains new Date().toString(), not the contents of the file
fileName should surely contain the file's name, not its contents?