简体   繁体   中英

Getting image from server and saving to MySQL DB

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM