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();
}
Related
my application connects to a database in mysql using phpmyadmin and stores an image in the database, but my problem is when I download the image from the database and post the image on a imageview the image has a very low quality where also it's color is being afected too.
if I post the image directly on the database using phpmyadmin and then download the image using my app the image looks fine, but if I upload the image from my app and then i download it then the quality is bad.
the way to post the image is past the image to a byte[] and then uploading to the database that uses the type blob.
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;
}
can you help me please?
EDIT
#FXML
public void eventoBotonSeleccionarImagen() {
FileChooser imagenSeleccionada = new FileChooser();
FileChooser.ExtensionFilter filtroImagenjpg = new ExtensionFilter("Archivos *.jpg", "*.jpg");
FileChooser.ExtensionFilter filtroImagenJPG = new ExtensionFilter("Archivos *.JPG", "*.JPG");
File archivo = imagenSeleccionada.showOpenDialog(null);
try {
BufferedImage bufferedImage = ImageIO.read(archivo);
Image image = SwingFXUtils.toFXImage(bufferedImage, null);
imageViewMonstruo.setImage(image);
}
catch(Exception e) {
e.printStackTrace();
}
}
I found the answer to the question thanks to this
this question.
What I've done is changing from Blob to longblob in the database and adding png instead of jpg, the code result is this
private byte[] imagenToByte(Image imagen) {
BufferedImage bufferimage = SwingFXUtils.fromFXImage(imagen, null);
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
ImageIO.write(bufferimage, "png", output );
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte [] data = output.toByteArray();
return data;
}
And finally it upload and download the images with the same quality
I have to add result at the last column of each row. I have to test user successfully login with correct email and password the "PASS" is append to last else "FAIL" and go with the second row and check the result of each row.
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver", "D:\\Automation\\Selenium Drivers\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("http://www.facebook.com");
// This will load csv file
CSVReader reader = null;
try{
reader = new CSVReader(new FileReader("C:\\Users\\src\\com\\elements\\demo.csv"));
}catch (Exception e) {
e.printStackTrace();
}
String[] cell;
while ((cell=reader.readNext())!=null){
for(int i=0;i<1;i++){
String emailid=cell[i];
String password=cell[i+1];
driver.findElement(By.id("email")).sendKeys(emailid);
driver.findElement(By.id("pass")).sendKeys(password);
driver.findElement(By.id("loginbutton")).click();
String outputFile = "C:\\Users\\src\\com\\elements\\demo.csv";
try {
// use FileWriter constructor that specifies open for appending
CsvWriter csvOutput = new CsvWriter(new FileWriter(outputFile, true),',');
if(driver.getTitle().equals("Log1 in to Facebook | Facebook"))
{
csvOutput.write("Pass"); //Your selenium result.
//csvOutput.endRecord();
//csvOutput.close();
}
else if (driver.getTitle().equals("Log in to Facebook | Facebook"))
{
csvOutput.write("userName");
csvOutput.write("password");
csvOutput.write("Fail"); //Your selenium result.
csvOutput.endRecord();
csvOutput.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Try this code.
String outputFile = "test.csv";
// before we open the file check to see if it already exists
boolean alreadyExists = new File(outputFile).exists();
try {
// use FileWriter constructor that specifies open for appending
CsvWriter csvOutput = new CsvWriter(new FileWriter(outputFile, true),',');
// if the file didn't already exist then we need to write out the header line
if (!alreadyExists){
csvOutput.write("result");
csvOutput.endRecord();
}
// else assume that the file already has the correct header line
// write out a few records
csvOutput.write("userName");
csvOutput.write("password");
csvOutput.write("Pass/Fail"); //Your selenium result.
csvOutput.endRecord();
csvOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
OR
If we want to use writeNext() method which take string array as a parameter then
String csv = "D:\\test.csv";
CSVWriter writer = new CSVWriter(new FileWriter(csv));
List<String[]> data = new ArrayList<String[]>();
data.add(new String[] {"India", "New Delhi"});
data.add(new String[] {"United States", "Washington D.C"});
data.add(new String[] {"Germany", "Berlin"});
writer.writeAll(data);
writer.close();
Try other option.
FileWriter writer = new FileWriter("D:/test.csv",false);
writer.append(" ");
writer.append(',');
writer.append("UserName");
writer.append(',');
writer.append("Password");
writer.append(',');
writer.append("Pass/Fail");
writer.append('\n');
//generate whatever data you want
writer.flush();
writer.close();
I have a database named as "test" in which I have a table named as "first" which contains raw data, I want to get this table data. What should be the prepare statement I have to use in order to get data from table "first" ? Below is the code I am trying. Any help or guidance would be appreciable.
#Path("/database") // Specific URL
#GE
#Produces(MediaType.TEXT_PLAIN)
public String returnDB_Status() throws Exception {
PreparedStatement query = null;
String result = null;
Connection conn = null;
try {
conn = mysql_prac.dbConn().getConnection(); // this works fine ...
query = conn.prepareStatement("SELECT * from first" ); // Table named as "first" is placed inside the connected database.
ResultSet rs = query.executeQuery();
result = "Data received : " + rs;
query.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null)
conn.close();
}
return result;
}
and the source code used get a connection
public class mysql_prac {
private static DataSource mysql_prac = null;
private static Context context = null;
public static DataSource dbConn() throws Exception {
if (mysql_prac != null) {
return mysql_prac;
}
try {
if (context == null) {
context = new InitialContext();
}
mysql_prac = (DataSource) context.lookup("JDBC_ref"); //JNDI ID (JDBC_REF)
} catch (Exception e) {
e.printStackTrace();
}
return mysql_prac;
}
}
You must loop through the ResultSet to get the fields of each row. So I made the following edit together with some comments.Please notice the comments.
try {
conn = mysql_prac.dbConn().getConnection(); // this works fine ...
query = conn.prepareStatement("SELECT * from first" ); // Table named as "first" is placed inside the connected database.
ResultSet rs = query.executeQuery();//You must loop through the results set to get the fields of each row
while(rs.next()){
String dbUserID = rs.getString("column1");//this is just an example to retrieve all data in the column called 'column1'
result = "Data received : " + dbUserID;
System.out.println(result);
}
query.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null)
conn.close();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try
{
Class.forName("java.sql.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "parin");
Statement stmt=con.createStatement();
String query="Select * from Liblogin;";
ResultSet rs=stmt.executeQuery(query);
String username=rs.getString("username");
String password=rs.getString("password");
rs.close();
stmt.close();
con.close();
String enteredUsername=t1.getText().toString();
String enteredPassword = new String(t2.getText());
if(enteredUsername.contentEquals(username)&&enteredPassword.contentEquals(password))
{
Homepage a=new Homepage();
a.setVisible(true);
this.dispose();
}
else
{
JOptionPane.showMessageDialog(this,"Incorrect name and password.");
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this, e);
}
}
I am trying to retrieve my password and username from mysql database.But unable to do so because of some exception(Sql exception:Before start of result set.).
You need to call rs.first(); or rs.next(); before trying to read the values from a ResultSet row.
http://docs.oracle.com/javase/6/docs/api/java/sql/ResultSet.html#first%28%29
Calling rs.next(); is especially handy in a while-loop to process all the rows in the ResultSet.
// Get a result set from SQL query
while (rs.next()) {
// Process this row
}
My goal is to centralize all the interactions with my MySql database in a single class (e.g. SqlUtils). I basically want to maintain access to ResultSet or a similar class even after the connection is closed. The following way doesn't work as after my business method receives the ResultSet, an exception is thrown because the underlying connection is already closed. I want to emphasize that opening and closing a connection to the database has to take place inside getResultSet().
public ResultSet getResultSet(String sql) {
try (Connection conn = getConnection();){
return conn.createStatement().executeQuery(sql);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
What I'm now thinking to do is something like this:
public List<ResultHolder> getResultSet(String sql) {
List<ResultHolder> list = new LinkedList<>();
try (Connection conn = getConnection();
ResultSet res = conn.createStatement().executeQuery(sql);) {
while(res.next()) {
list.add(res.convertToResultHolder());
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
Is there any class that does what I need, which I expressed as ResultHolder.
If you want to have access to all the resultset data even after connection is closed then I would suggest following:
public List<Map<String, Object>> getResultSet(String sql) {
// this list will hold all the data returned from resultset
List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
try (Connection conn = getConnection();
ResultSet rs = conn.createStatement().executeQuery(sql);) {
while(rs.next()) {
// this map corresponds to each row of the resultset
// key: column-name, value: column-value
Map<String, Object> row = new LinkedHashMap<String, Object>();
// populate each row using resultset's Meta data
ResultSetMetaData meta = rs.getMetaData();
for (int i=1; i<=meta.getColumnCount(); i++)
row.put(meta.getColumnName(i), rs.getObject(i));
rows.add(row);
}
} catch (Exception e) {
e.printStackTrace();
}
return rows;
}