Search code examples
javajdbcblobresultset

Read Blob file without saving it a file


I have planned to encrypt a string using a public key which is stored in a database as Blob.I have created method called readBlob() to read the key and save it to the file.

  public static void readBlob(int userid, String filename) throws SQLException, IOException {
      String url = "jdbc:mysql://localhost:3306/bank";
        String user = "root";
        String password = "root";
        String email=null;

            Connection conn = DriverManager.getConnection(url, user, password);
            String sql = "select * from users where user_id=?";
            PreparedStatement statement = conn.prepareStatement(sql);
            statement.setLong(1, userid);
            ResultSet result = statement.executeQuery();
            File file = new File(filename);
            @SuppressWarnings("resource")
            FileOutputStream output = new FileOutputStream(file);
            String keys=null;

    while(result.next()) {
         byte[] buffer = new byte[1];
         InputStream input = result.getBinaryStream("key");
         while (input.read(buffer) > 0) {
             output.write(buffer);
            }        
        }
  }

It worked really well but I don't need to save it to the local file ,I need a way to read the Blob without saving it.


Solution

  • You can use getBlob

    Blob key = result.getBlob("key")
    

    Retrieves the value of the designated column in the current row of this ResultSet object as a Blob object in the Java programming language.