Display multiple Blob files from mySQL - mysql

I want to create a gallery in a java web app project. The gallery reads images that are stored as BLOB files in a mySQL DB. This is what I have done but only the first Image in the db displays. Is it possible to read multiple BLOB images from a db or would I be better off creating a gallery from images stored in a folder?
<%# page import="java.sql.*"%>
<%# page import="java.io.*"%>
<%
Blob image = null;
Connection con = null;
byte[ ] imgData = null ;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/capture","root","");
stmt = con.createStatement();
rs = stmt.executeQuery("select file from photoentry");
if (rs.next()) {
image = rs.getBlob(1);
imgData = image.getBytes(1,(int)image.length());
}
else {
out.println("Display Blob Example");
out.println("image not found for given id>");
return;
}
// display the image
response.setContentType("image/jpg");
OutputStream o = response.getOutputStream();
o.write(imgData);
o.flush();
o.close();
} catch (Exception e) {
out.println("Unable To Display image");
out.println("Image Display Error=" + e.getMessage());
return;
} finally {
try {
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
%>

Related

My code not displaying image on chrome browser but works find on internet explorer

I'm trying to display image from MySQL server on to the browser. But the following code works on Internet Explorer but not working on Chrome and Mozilla Firefox browser.
I'm new to JSP and I've already tried code from this question but didn't work .Displaying image in jsp from database
`<%# include file="connect.jsp" %>
<%#page import="java.sql.*,java.io.*"%>
<%# page import="java.sql.*,java.io.*,java.util.*" %>
<%
try{
int id = Integer.parseInt(request.getParameter("id"));
Statement st=connection.createStatement();
String strQuery = "select image from user where id="+id+"" ;
ResultSet rs = st.executeQuery(strQuery);
String imgLen="";
if(rs.next())
{
imgLen = rs.getString(1);
}
rs = st.executeQuery(strQuery);
if(rs.next())
{
int len = imgLen.length();
byte [] rb = new byte[len];
InputStream readImg = rs.getBinaryStream(1);
int index=readImg.read(rb, 0, len);
st.close();
response.reset();
response.getOutputStream().write(rb,0,len);
response.getOutputStream().flush();
}
}
catch (Exception e){
e.printStackTrace();
}%>
To retrieve multiple images from the SQL database and display in JSP pages you can do this:
<%
int id = Integer.parseInt(request.getParameter("imgid"));
try {
Connection con=DriverManager.getConnection("jdbc:sqlserver://XXXXX\\SQLEXPRESS14;databaseName=Student;user=XX;password=XXXXX");
Statement st = con.createStatement();
String strQuery = "select image from login_users where id='" + id + "'";
ResultSet rs = st.executeQuery(strQuery);
String imgLen="";
if(rs.next()) {
imgLen = rs.getString(1);
}
rs = st.executeQuery(strQuery);
if(rs.next()) {
byte[] bytearray = new byte[4096];
int size=0;
InputStream sImage = rs.getBinaryStream(1);
response.reset();
response.setContentType("image/jpeg");
while((size=sImage.read(bytearray))!= -1) {
response.getOutputStream().write(bytearray,0,size);
}
response.getOutputStream().flush();
response.getOutputStream().close();
response.flushBuffer();
sImage.close();
rs.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
%>

Uploading an image to a database with javafx

i'm trying to upload an image to mysql database using phpmyadmin and despite the program works and stores the rest of the data the image is not stored correctly.
If I upload an image directly in phpmyadmin the image's size in type Blob it's 26.6 KB but if I try to uploading using javafx the image's size it's about 10 B so I think i'm not uploading correctly.
#Override
public void guardarMonstruo(MonstruoDTO monstruo) {
con= ConexionBDA.getInstance().getCon();
try {
if (con != null){
byte[] blob = imagenToByte(monstruo.getImagen());
System.out.println(blob.toString());
statement = con.createStatement();
statement.executeUpdate("INSERT INTO monstruos (Nombre,Habitat,Estado,ColaCercenable,DragonAnciano,DebilidadFuego,DebilidadAgua,Debilidadrayo,DebilidadHielo,DebilidadDraco,ImagenMonstruo) VALUES ('"+monstruo.getNombre()+"'"+","+"'"+monstruo.getHabitat()+"'"+","+"'"+monstruo.getEstado()+"'"+","+"'"+monstruo.getColaCercenable()+"'"+","+"'"+monstruo.getDragonAnciano()+"'"+","+"'"+monstruo.getDebilidadFuego()+"'"+","+"'"+monstruo.getDebilidadAgua()+"'"+","+"'"+monstruo.getDebilidadRayo()+"'"+","+"'"+monstruo.getDebilidadHielo()+"'"+","+"'"+monstruo.getDebilidadDraco()+"'"+","+"'"+blob+"');");
con.close();
statement.close();
}
}
catch(Exception e) {
e.printStackTrace();
}
}
And the method imagenToByte() is used to pass the image to byte is this:
private byte[] imagenToByte(Image imagen) {
BufferedImage bufferimage = SwingFXUtils.fromFXImage(imagen, null);
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
ImageIO.write(bufferimage, "jpg", output );
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte [] data = output.toByteArray();
return data;
}
I don't know what i'm doing wrong, could you please help me?
You insert the result of the toString method to the query string which won't result in the desired outcome. Use PreparedStatement and set a Blob parameter instead:
try (PreparedStatement ps = con.prepareStatement("INSERT INTO monstruos (Nombre,Habitat,Estado,ColaCercenable,DragonAnciano,DebilidadFuego,DebilidadAgua,Debilidadrayo,DebilidadHielo,DebilidadDraco,ImagenMonstruo) VALUES (?,?,?,?,?,?,?,?,?,?,?)")) {
ps.setString(1, monstruo.getNombre());
ps.setString(2, monstruo.getHabitat());
ps.setString(3, monstruo.getEstado());
ps.setString(4, monstruo.getColaCercenable());
ps.setString(5, monstruo.getDragonAnciano());
ps.setString(6, monstruo.getDebilidadFuego());
ps.setString(7, monstruo.getDebilidadAgua());
ps.setString(8, monstruo.getDebilidadRayo());
ps.setString(9, monstruo.getDebilidadHielo());
ps.setString(10, monstruo.getDebilidadDraco());
// upload the data, not the toString result of the array
ps.setBlob(11, new SerialBlob(blob));
ps.executeUpdate();
}

Export excel from MySQL database using JSP

This is my JSP coding, I am using link to redirect to JSP page :
Excel.jsp
<%#page import="java.sql.*"%>
<%#page import="java.sql.SQLException"%>
<%#page import="org.apache.poi.hssf.usermodel.*"%>
<%#page import=" java.io.*"%>
<%
String url = "jdbc:mysql://localhost:3306/";
String dbName = "login";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
try {
Class.forName("driver");
Connection con = DriverManager.getConnection("url + dbName", "userName",
"password");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from openstock");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("fisocon");
HSSFRow rowhead = sheet.createRow((short) 0);
rowhead.createCell((short) 0).setCellValue("iname");
rowhead.createCell((short) 1).setCellValue("wname");
rowhead.createCell((short) 2).setCellValue("catname");
rowhead.createCell((short) 3).setCellValue("class");
rowhead.createCell((short) 4).setCellValue("unit");
rowhead.createCell((short) 5).setCellValue("nname");
int i = 1;
while (rs.next()){
out.println("hai2");
HSSFRow row = sheet.createRow((short) i);
row.createCell((short)
0).setCellValue(Integer.toString(rs.getInt("iname")));
row.createCell((short) 1).setCellValue(rs.getString("wname"));
row.createCell((short) 2).setCellValue(rs.getString("catname"));
row.createCell((short) 3).setCellValue(rs.getString("class"));
row.createCell((short) 4).setCellValue(rs.getString("unit"));
row.createCell((short) 5).setCellValue(rs.getString("nname"));
i++;
}
String yemi = "d:/xls/test.xls";
FileOutputStream fileOut = new FileOutputStream(yemi);
workbook.write(fileOut);
fileOut.close();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
catch (SQLException e1) {
e1.printStackTrace();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
%>
In this coding, createcell is strikeout. I don't know why it is.
There is no errors in coding. I also add poi 3.14 jar file in library.
My output page displays as empty. Please help me. Thanks in advance.
Page is empty because everything You made is outside of page.
BTW doing such in JSP is the worst idea.
Move this code to servlet, here is tip how to return binary data.
java servlet response returning data
Add
response.contentType = "application/vnd.ms-excel"
and JPS page should only have link
The additional effect: servlet code is more, more friendly to debugging.

Export MYSQL rows into several txt files

I have a MYSQL database with 50.000 rows. Each row represents an article. I want the value of the column with they name "articletext" to be split into 50.000 files. One file for each row. I'm new to MYSQL so I'm not sure how to do this.
Can anyone help me?
Thanks
I created this small java application to solve the problem.
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Opening connection");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost/articles", "username", "password");
String query = "Select title,articletext from articles";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String title = rs.getString(1);
String text = rs.getString(2);
try {
FileWriter fstream = new FileWriter(title + ".txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(text);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("Closing connection");
con.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And I propose my solution using Python:
import MySQLdb
def write_to_file(with_name, write_this):
with_name = str(with_name)
with open(with_name, "w") as F:
F.write(write_this)
db = MySQLdb.connect(
host="localhost", # hostname, usually localhost
user="andi", # your username
passwd="passsword", # your password
db="db_name", # name of the database
charset = "utf8", # encoding
use_unicode = True
)
cur = db.cursor()
cur.execute("select id, description from SOME_TABLE")
for row in cur.fetchall() :
write_to_file(row[0], row[1].encode('utf8'))
where row[0] will map to id, row[1] will map to description

How to display an image from the DB in JSP?

I need to retrieve image from MySQL DB.
I got a code snippet from somewhere but could not display the image properly in the jQuery panel.
The code runs in a new JSP page.
Can anyone tell me how to use outputstream effectively in my application?
The code I have is:
<% #page import = "java.sql.*" %>
<% #page import = "java.io.*" %>
<% Blob image = null;
Connection con = null;
byte[] imgData = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/aes", "root", "password");
stmt = con.createStatement();
rs = stmt.executeQuery("select PHOTO from tab_1 where name ='" + name + "'");
if (rs.next()) {
image = rs.getBlob(1);
imgData = image.getBytes(1, (int) image.length());
} else {
out.println("image not found for given id>");
return;
}
// display the image
response.setContentType("image/gif");
OutputStream o = response.getOutputStream();
o.write(imgData);
o.flush();
o.close();
} catch (Exception e) {
out.println("Unable To Display image");
out.println("Image Display Error=" + e.getMessage());
return;
} finally {
try {
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
%>
JSP is the wrong tool for this. JSP is a view technology. Any whitespace outside the <% %> will also be printed/sent to the response. It's in your case exactly that whitespace which malforms the binary integrity of the image and thus the image ends up being corrupted and unrenderable.
You have basically 2 options.
The simple/lazy way: remove all, I really mean all, whitespace outside <% %> including newlines.
Use the right tool: create a class which extends HttpServlet and move the code which you've there in the JSP into the doGet() method. Finally just call that servlet instead of the JSP.