Having trouble reading data from SQL database - java

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.

Related

Updating JLabel via SetIcon from bytea data type in postgres

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();
}

JavaFX,SQLite : How to Set BLOB Value in update Query?

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)

Getting blob image in mysql using restful web service

I've done listing the strings like the name etc. but I've got problem in retrieving the image. Here's my code of retrieving it. It is in the arraylist. I don't know if i'm getting the right output. Please help me. Here's my code
public ArrayList<Objects> getTaxiDetails(Connection con, String taxi_plate_no) throws SQLException{
ArrayList<Objects> taxiDetailsList = new ArrayList<Objects>();
PreparedStatement stmt = con.prepareStatement("SELECT * from taxi_driver where taxi_plate_no = '" +taxi_plate_no+ "'");
//PreparedStatement stmt = con.prepareStatement("SELECT * from taxi_driver");
ResultSet rs = stmt.executeQuery();
try{
byte[] bytes = null;
while(rs.next()){
Objects taxiObjects = new Objects();
taxiObjects.setDriver_contact_no(rs.getString("driver_contact_no"));
taxiObjects.setDriver_name(rs.getString("driver_name"));
taxiObjects.setTaxi_plate_no(rs.getString("taxi_plate_no"));
taxiObjects.setDriver_operator(rs.getString("driver_operator"));
taxiObjects.setDriver_operator_address(rs.getString("driver_operator_address"));
taxiObjects.setImage(rs.getBytes("image"));
Blob image = rs.getBlob(1);
byte[] allBytesInBlob = image.getBytes(1, (int) image.length());
taxiDetailsList.add(taxiObjects);
}
} catch (SQLException e){
e.printStackTrace();
} return taxiDetailsList;
}
Here's the output

Issue with getBinaryStream(index)

I am getting null value when I am reading the blob data from database. What might be the issue? Can some one help me on this?
Connection con = null;
PreparedStatement psStmt = null;
ResultSet rs = null;
try {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
con =
DriverManager.getConnection("jdbc:oracle:thin:#MyDatabase:1535:XE","password","password");
System.out.println("connection established"+con);
psStmt = con
.prepareStatement("Select Photo from Person where Firstname=?");
int i = 1;
psStmt.setLong(1, "Nani");
rs = null;
rs = psStmt.executeQuery();
InputStream inputStream = null;
while (rs.next()) {
inputStream = rs.getBinaryStream(1);
//Blob blob = rs.getBlob(1);
//Blob blob1 = (Blob)rs.getObject(1);
//System.out.println("blob length "+blob1);//rs.getString(1);
}
System.out.println("bytessssssss "+inputStream);//here i am getting null value.
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I believe you didn't use setString function to assign any value to firstname which leads to null
for example:
ps.preparedStatement("Select photo from person where firstname = ?");
ps.setString(1,"kick"); <----- add this line
system.out.println("bytes "+rs.getBinaryStream(1));
Another suggestions
there is no need to use rs = null; inside try catch block because you have rs=null; at beginning of
your code.
change
InputStream inputStream = null;
to
InputStream inputStream = new InputStream();
or
get rid of InputStream inputStream = null;
source you should take a look at
The most obvious error is using setLong instead of setString.
However one practice is fatal: declaring in advance. This in other languages is a good practice, but in java one should declare as close as possible.
This reduces scope, by which you would have found the error! Namely inputStream is called after a failed rs.next() - outside the loop. Maybe because no records were found.
This practice, declaring as near as feasible, also helps with try-with-resources which were used here to automatically close the statement and result set.
Connection con = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(
"jdbc:oracle:thin:#MyDatabase:1535:XE","password","password");
System.out.println("connection established"+con);
try (PreparedStatement psStmt = con.prepareStatement(
"Select Photo from Person where Firstname=?")) {
int i = 1;
psStmt.setString(1, "Nani");
try (ResultSet rs = psStmt.executeQuery()) {
while (rs.next()) {
try (InputStream inputStream = rs.getBinaryStream(1)) {
//Blob blob = rs.getBlob(1);
//Blob blob1 = (Blob)rs.getObject(1);
//System.out.println("blob length "+blob1);//rs.getString(1);
Files.copy(inputStream, Paths.get("C:/photo-" + i + ".jpg"));
}
++i;
}
//ERROR System.out.println("bytessssssss "+inputStream);
} // Closes rs.
} // Closes psStmt.
}
1- In your code when setting the parameter's value of SQL query, be sure to use the appropriate data type of the field. So here you should use
psStmt.setString(1, "Nani");
instead of
psStmt.setLong(1, "Nani");
2- Make sure that the query is correct (Table name, field name).
3- Make sure that the table is containing data.

Cannot retrieve blob data and display in JLabel- mySql

First time posting, hoping for some help. I have been through all similar postings on this forum...and believe the code used to be correct, however it continues to return nullpointerException. The program is a simple employee database, entering employee details along with picture. This is working fine, can insert image to blob field in mySql no problem. However, I simply cannot retrieve and display in JLabel.
The following code is the final part of the program, where the user can simply insert name of employee to retrieve all details. the search function is as follows:
void search(){
try {
st = cn.createStatement();
byte[] imageBytes;
Image image;
ResultSet rs=st.executeQuery("SELECT * FROM info WHERE pname='"+ txtSearch.getText() + "'");
if(rs.next()){
txtName.setText(rs.getString("Pname").toString());
if (rs.getString("sex").toString().equals("Male")){
cboGender.setSelectedIndex(0);
}else{
cboGender.setSelectedIndex(1);
}
txtAddress.setText(rs.getString("address").toString());
txtPosition.setText(rs.getString("position").toString());
txtSecurityLvl.setText(rs.getString("security").toString());
try {
String sql = ("select photograph from info where pname ='" + txtSearch.getText() + "'");
ps = cn.prepareStatement(sql);
rs = ps.executeQuery();
if (rs.next()) {
byte[] imagedata= rs.getBytes("photograph");
format=new ImageIcon(imagedata);
picLabel2.setIcon(format);
}
} catch (Exception e) {
e.printStackTrace();
}
/*
try {
BufferedImage img = ImageIO.read(rs.getBinaryStream("photograph"));
picLabel.setIcon(new ImageIcon(img));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//picLabel.setIcon(new ImageIcon(ByteStreams.toByteArray(Blob.getBinaryStream())));
*/
}else{
JOptionPane.showMessageDialog(null,"Not Found",null, JOptionPane.INFORMATION_MESSAGE, null);
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
Any help is is very much appreciated, this should be a simple task, but have been looking at it for so long that I cant see for looking. Thanks!
*nb- the mySql Db table is 'info', the column with containing blob is 'photograph'
Updated: The program should populate the respective textfields with name, address etc, and display the employee photo in a corresponding label. The textfields are populated but the program crashes at this line: picLabel2.setIcon(format); returning a nullPointerException () **line 630
You have not initialized picLabel2. (Judging from the error)
Somewhere above picLabel2.setIcon(format);, you will need to do the following:
JLabel picLabel2 = new JLabel();
You may also still want to set text on the label, if that is required, then you can either:
Pass it as String in the constructor.
Call picLabel2.setText(string).

Categories

Resources