简体   繁体   中英

Java -How to retrieve multiple blob images from MySQL

I am quite new to java and mysql and I am trying to retrieve multiple (a lot!) blob images from a mysql-database.
I need some sort of loop-query to get through all of the images.

I started with a tutorial ( http://www.roseindia.net/java/java-get-example/get-blob.shtml ) and this works great for me. - keep in mind, that I am looking to get the pictures straight to my computer.

Do you guys have any suggestions on how to expand the existing code in order to retrieve not one but multiple images?

This is the code I am using:

class GetBlob {
    FileOutputStream image;
    Connection con = null;
    PreparedStatement pstmt = null;
    Statement stmt = null;
    ResultSet res = null;
    StringBuffer query = null;
    String driverName = "com.mysql.jdbc.Driver";
    String url = "jdbc:mysql://localhost:3306/";;
    String dbName = "portal";
    String userName = "root";
    String password = "xxxx";

public GetBlob() {
    try {
        Class.forName(driverName);
        con = DriverManager.getConnection(url + dbName, userName, password);
        stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("select * from pictures where id='1'");
        if (rs.next()) {
            Blob test = rs.getBlob("picture");
            InputStream x = test.getBinaryStream();
            int size = x.available();
            OutputStream out = new FileOutputStream("/Users/User/Desktop/anu2.jpg");
            byte b[] = new byte[size];
            x.read(b);
            out.write(b);
        }
    } catch (Exception e) {
        System.out.println("Exception :" + e);
    } finally {
        try {
            stmt.close();
            con.close();
        } catch (Exception e) {
            System.out.println(e);
        }
      }
   }

public static void main(String args[]) throws IOException {
    GetBlob blob = new GetBlob();
   }
}

Hint

Zero int should not be between two 'id'


First You can make some changes in your query and in your GetResult:

Your query should look like :

"select * from pictures" -- without where because if the id is unique you will get only one

Or you can use IN :

"select * from pictures where id IN (id1, id2, id3, ...)"

Second To get multiple results, you have to a List instead.

and instead of if(rs.next()) you have to loop throw your result with while(rs.next())


Third If you want to return your values, you have to use a method instead, and not call your Constructor.

public static List<Images> getImages(){
   ...
}

Forth To avoid any kind of Syntax error, or SQL Injection you have to PreparedStatement instead.


Hope this instruction can help you, and gives you an idea, good luck.

Performing multiple queries may be cumbersome and not efficient.

You could use a PreparedStatement and specify a IN clause in your query but you could not set a list of parameter with.
A simple and efficient alternative way would be to create the query dynamically with as many ? as the size of the input list id. Then execute the query and iterate on the ResultSet and apply the processing unitary that you have used to get the blob from the ResultSet .

A not tested sample code :

List<Integer> ids = ...; // the ids you want to use for your query
String sql= createQuery(ids);    
PreparedStatement preparedStatement = dbConnection.prepareStatement(sql);
for (int i=0; i< ids.size(); i++){
    int id = ids.get(i);
    preparedStatement.setInt(i+1, id);
}

ResultSet rs = stmt.executeQuery(sql);

while (rs.next()) {
  // your actual code
     Blob test = rs.getBlob("picture");
     InputStream x = test.getBinaryStream();
     int size = x.available();
     OutputStream out = new FileOutputStream("/Users/User/Desktop/anu2.jpg");
     byte b[] = new byte[size];
     x.read(b);
     out.write(b);
}


private String createQuery(List<Integer> ids){
  String query = "select * from pictures where id IN(";

  for (int i=0; i< ids.size(); i++){          
       if (i>0){
          query += ",";   
       }

       query += "?";
  }

  query += ")";  
  return query;
}

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