Getting blob image in mysql using restful web service - java

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

Related

Having trouble reading data from SQL database

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.

How to write fetched values from database to Excel file

I need your help in storing the fetched values from a SQL statement to an excel file. I wrote the below code, but I am facing difficulties on how to write the fetched values under the appropriate columns. For example at the beginning, I created 3 headers (ID - Name - Salary). Now, I need to write the fetched values from the SQL statement under each appropriate header, but I do not know how to write them. So kindly assist. The code is:
public void GenerateExcel() {
Connection conn = null;
Statement stmt = null;
FileOutputStream fileOut = new FileOutputStream("C:\\Desktop\\poi-test.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet worksheet = workbook.createSheet("Employee Details");
HSSFRow row1 = worksheet.createRow((short) 0);
HSSFCell cellA1 = row1.createCell((short) 0);
cellA1.setCellValue("ID");
HSSFCell cellB1 = row1.createCell((short) 1);
cellB1.setCellValue("Name");
HSSFCell cellC1 = row1.createCell((short) 1);
cellC1.setCellValue("Salary");
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String sql = "SELECT id, name, amount FROM Employee";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
int age = rs.getString("name");
String first = rs.getInt("amount");
}
rs.close();
workbook.write(fileOut);
fileOut.flush();
fileOut.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
}
Actually I can't see where you add data to the workbook ?
I can only see you creating the workbook and adding the first row.
while(rs.next()){
int id = rs.getInt("id");
int age = rs.getString("name");
String first = rs.getInt("amount");
// Adding data here
Row newRow = worksheet.createRow(worksheet.getLastRowNum() + 1);
newRow.createCell(0).setCellValue(id);
newRow.createCell(1).setCellValue(age);
newRow.createCell(2).setCellValue(first);
}
Finally stop wasting time writing apache poi boiler plate. Look at MemPOI's solution:
You can try using MemPOI. Take a look:
File file = new File("C:\\Desktop\\poi-test.xls")
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
PreparedStatement prepStmt = this.connection.prepareStatement("SELECT id, name, amount FROM Employee");
new MempoiBuilder()
.setFile(file)
.addMempoiSheet(new MempoiSheet(prepStmt, "Employee Details"))
.build()
.prepareMempoiReportToFile()
.get();
You can easily add a template or a subfoter. Take a look at the doc

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.

How do I connect to data base from servlet. I have tried the following code, but control goes to exception everytime

How do I connect to data base from servlet. I have tried the following code, but control goes to exception everytime.
try
{
int num_rows = 0;
Connection con = null;
Statement st = null;
Statement search = null;
ResultSet rs = null;
ResultSet searchRS = null;
// Connecting to the database
PrintWriter out = response.getWriter();
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/employees","root","");
st = con.createStatement();
rs = st.executeQuery("select employees.first_name,employees.last_name,employees.gender,employees.hire_date,departments.dept_name,salaries.salary from employees,departments,salaries,dept_emp where employees.emp_no=salaries.emp_no AND dept_emp.emp_no=employees.emp_no AND dept_emp.dept_no=departments.dept_no AND salaries.to_date='9999-01-01' AND (employees.first_name='"+Sname+"' OR employees.last_name='"+Sname+"')");
//Retrieval of data from result set retrieved from database
String[][] str = new String[10][6];
while( rs.next())
{
str[num_rows][0] = rs.getString("first_name");
str[num_rows][1] = rs.getString("last_name");
str[num_rows][2] = rs.getString("gender");
str[num_rows][3] = rs.getString("hire_date");
str[num_rows][4] = rs.getString("dept_name");
str[num_rows][5] = rs.getString("salary");
num_rows++;
}
if(num_rows <10)
{
isLast = true;
var = 0;
}
request.setAttribute("listvalue",str);
request.setAttribute("rows",num_rows);
RequestDispatcher RequestDispatcherObj =request.getRequestDispatcher("SearchName.jsp");
RequestDispatcherObj.forward(request, response);
out.flush();
con.close();
var = var +10;
}
catch(Exception e)
{
e.printStackTrace();
}
Your string array can hold 10 records; probably you are getting more than that from the database.
You may try this-
while( rs.next() && num_rows < 10 )
In case you need to collect all the records, better use some collection like List.
For me looks like the line
RequestDispatcherObj.forward(request, response);
is creating the problem. It is forwarding the request to some other place. The requestdispatcheobj may have closed the out object. So after that use of flush() and write() will lead to an IllegalStateException.
out.flush();
con.close();
var = var +10;
So make sure this is not the case.

How to obtain text stored in Mysql Mediumblob through Java?

I'm a beginner in Java and am not understanding how to obtain a paragraph of text that I have stored in Mysql database as a Mediumblob through Java. Below is the section of my code that I'm having problems with. I've successfully obtained other stored data in the form of VARCHAR and INT through .getString() and .getInt(). I did try .getObject() below but that didn't seem to work. Any insight would be appreciated ~ thank you.
try{
con = DriverManager.getConnection(url, user, password);
pst = con.prepareStatement("SELECT * FROM exercise WHERE exercise_name = Clams;");
rs = pst.executeQuery();
while (rs.next()){
java.sql.Blob id = rs.getBlob("description");
System.out.print(id);
}
}catch(SQLException ex){
}finally {
try {
if (rs != null){
rs.close();
}
if (pst != null){
pst.close();
}
if (con != null){
con.close();
}
}catch(SQLException ex){
}
}
}
try this
java.sql.Blob id = rs.getBlob("description");
String s = new String(id.getBytes(0,id.length()));

Categories

Resources