ok, the below statement works with there wasnt a row create. and in my code i push a file into my database with binary stream and in the code below you see this, and it works but i need it to update a row instead of insert, how would i do that?
JFileChooser fc = new JFileChooser();
fc.showOpenDialog(this);
File f = fc.getSelectedFile();
File j = f;
//String path = f.getAbsolutePath();
//picPreview.setIcon(new ImageIcon(path));
try{
BufferedImage image = ImageIO.read(j);
BufferedImage scaled = getScaledInstance(
image, picPreview.getWidth(), picPreview.getHeight(), RenderingHints.VALUE_INTERPOLATION_BILINEAR, true);
picPreview.setIcon(new ImageIcon(scaled));
}catch(Exception ex){
}
try{
FileInputStream fin = new FileInputStream(f);
int len = (int)f.length();
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/newbieswithauctions","root","root");
PreparedStatement ps = con.prepareStatement("INSERT INTO listings(itemPicture) VALUES(?)");
ps.setBinaryStream(1, fin, len);
int status = ps.executeUpdate();
if(status>0){
jLabel2.setText("Successfully uploaded image to database");
}
else{
jLabel2.setText("Upload Failed!");
}
}catch(Exception e )
{
JOptionPane.showMessageDialog(null,e, "Error ", JOptionPane.ERROR_MESSAGE);
}
i tried to put VALUES(?) and i used a variable i had but i failed miserably
"UPDATE listings SET itemPicture=VALUES(?) WHERE itemVin='" + VinNum + "'");
Related
why my download file always got corrupted.
I have a code that will upload file using blob.
the code is
InputStream inputStream = new FileInputStream(new File(filePath)); //the file to upload
pst.setBinaryStream(15, inputStream); //to upload the selected file
it's successfully upload to my sql data base but when I try to download it, it always got corrupted.
below is my code to download the file from sql.
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url1 = "jdbc:sqlserver://ets88-spare:1433;databaseName=users;user=sa;password=test";
Connection conn1 = DriverManager.getConnection(url1);
String query1 = "SELECT * FROM ets_verification";
Statement state = conn1.createStatement();
ResultSet rs = state.executeQuery(query1);
while (rs.next())
{
String boardname = jboardName.getSelectedItem().toString();
String sn = jserialNumber.getText();
String status = jverificationStatus.getSelectedItem().toString();
String filename = boardname + "_" + "_" + sn + "_"+ status;
byte[] array = rs.getBytes(16);
FileOutputStream fos = new FileOutputStream("c:\\" + filename + ".rar");
fos.write(array);
fos.close();
System.out.println("array:" + array);
}
}
catch (ClassNotFoundException | SQLException e)
{
jnote.setText(e.toString());
System.out.println("error" + e.toString());
} catch (IOException ex) {
Logger.getLogger(ets_verification.class.getName()).log(Level.SEVERE, null, ex);
}
You could try.
Tested in a ORACLE DB.
(...)
Blob blob = rs.getBlob(16);
if (blob != null) {
byte[] b = blob.getBytes(1, (int) blob.length());
try (FileOutputStream fos = new FileOutputStream("PATH/TO/FILE/FILENAME.rar")){
fos.write(file);
}catch (IOException ex) {
//Do something
}
}
(...)
As the title described, when I download the blob(audio) file from MySQL, things goes well and I get the file, but I can't play the audio immediately, unless I terminate the progress.
I guess the audio file is being occupated by the program, if so how can I solve this problem without terminate the program. thx!
Here the code:
public void downloadAudio(int documentid,String pathname) {
String sql = "SELECT storage FROM chatroom_tool WHERE documentid=?";
ResultSet rSet = null;
try {
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, documentid);
rSet = pstmt.executeQuery();
File file = new File(pathname);
FileOutputStream output = new FileOutputStream(file);
System.out.println("writing to file: " + file.getAbsolutePath());
while (rSet.next()) {
InputStream inputStream = rSet.getBinaryStream("storage");
byte[] buffer = new byte[1024];
while (inputStream.read(buffer) > 0) {
output.write(buffer);
}
}
System.out.println("downLoad success +++++");
} catch (SQLException | IOException e) {
e.printStackTrace();
}finally{
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Here is the picture when I open the audio without terminating the program.
image
inputStream.read does not have to fill the array with data completely, it returns the number of bytes it read. You must use the return value when you write the data to the output stream.
while ((bytes =inputStream.read(buffer)) >0)
output.write(buffer, bytes);
Also you have to close the output stream - Windows does not let other apps open the file as long as your program has it open
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();
}
Im getting an image from server as InputStream and then saving it to mySQL database. It works when I use Thread.sleep(5000);. But if I dont use it no picture is saved to the DB or only one picture and half of it or less. So I understand that the program needs time writing image to the database, but how much time? This is the question, I would like to know exactly when it finished writing image to the database and can start with the next image. Below is my code:
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
int ID = rs.getInt(1);
String myName = rs.getString(2);
try {
String myCommand = "take picture and save /mydir/mydir2/mydir3" + myName + ".png";
telnet.sendCommand(myCommand); // Here taking a picture via telnet
// Thread.sleep(5000);// If I uncomment this line it works
String sqlCommand = "UPDATE my_table SET Picture = ? WHERE ID ='" + ID +"';";
PreparedStatement statement = conn.prepareStatement(sqlCommand);
String ftpUrl = "ftp://"+server_IP+"/mydir/mydir2/mydir3" + myName + ".png;type=i";
URL url = new URL(ftpUrl);
URLConnection connUrl = url.openConnection();
//Thread.sleep(5000); // If I uncomment this line, it works too.
InputStream inputStreamTelnet = connUrl.getInputStream();
statement.setBlob(1, inputStreamTelnet);
int row = statement.executeUpdate();
if (row > 0) {
System.out.println("A picture was inserted into DB.");
System.out.println("Value of row(s) : " + row);
}
} catch (Exception e) {
e.printStackTrace();
}
} // End of while
I would expect to put the waiting(sleep) after InputStream inputStreamTelnet = connUrl.getInputStream(); but it doesnt work when I put the sleep after this line. It works only when the sleep is before. Could someone explain me why and I would like to avoid using Thread.sleep(5000); and instead would like to wait exact time or not wait at all which will make the program faster also there might be a case saving the picture can take more than 5 seconds or maybe saving the picture doesnt take time but opening the url connection. There are 2 sleep lines on the code when I uncomment one of them the program works(saves the images to mysql DB successfully). I also verified on the server that the images exist but in the end I dont see them in the mysql DB.
UPDATE : I removed the try block and telnet stuff now it works without waiting but I really need the telnet stuff...
UPDATE 2: After inspecting my telnet class found out that I forgot to apply a change I made to single line... now it works without wait!
Huh, I tested my code on JDK 1.7.0_67 / PostgreSQL 9.2 and it works well:
public class ImageLoader {
private static final int START_IMAGE_ID = 1;
private static final int END_IMAGE_ID = 1000;
private static final String IMAGE_URL = "http://savepic.net/%d.jpg";
public static void main(String[] args) throws SQLException, IOException {
Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/test", "username", "password");
PreparedStatement imageStatement = connection.prepareStatement("INSERT INTO public.image VALUES(?, ?)");
for (int i = START_IMAGE_ID; i <= END_IMAGE_ID; i++) {
String imageUrl = String.format(IMAGE_URL, i);
URL url = new URL(imageUrl);
URLConnection urlConnection = url.openConnection();
imageStatement.setLong(1, i);
imageStatement.setBytes(2, read(urlConnection.getInputStream()));
int count = imageStatement.executeUpdate();
if (count != 1) {
throw new IllegalStateException("Image with ID = " + i + " not inserted");
} else {
System.out.println("Image (" + imageUrl + ") saved to database");
}
}
imageStatement.close();
connection.close();
}
private static byte[] read(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1 << 15); // assume image average size ~ 32 Kbytes
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
byte[] buffer = new byte[1 << 10];
int read = -1;
while ((read = bufferedInputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, read);
}
return byteArrayOutputStream.toByteArray();
}
}
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?