0

I'm trying to save an image in a postgresql table

//table schema
CREATE TABLE public.hp_xray_results
(
  patient_no character varying(70),
  xray_image bytea
)

java.sql.PreparedStatement pstmt = connectDB.prepareStatement("INSERT INTO hp_xray_results (patient_no,xray_image) VALUES(?,?)");
pstmt.setString(1, jTextField36.getText());

File file = new File(String.valueOf(jTable3.getValueAt(i, 4)));
FileInputStream fis=null;
try {
    fis = new FileInputStream(file);
} catch (FileNotFoundException ex) {
    ex.printStackTrace();
    Exceptions.printStackTrace(ex);
}

pstmt.setBinaryStream(2, fis, (int) file.length());
try {
    fis.close();
} catch (IOException ex) {
    ex.printStackTrace();
    Exceptions.printStackTrace(ex);
}

pstmt.executeUpdate();

On running the above code, I get an exception. org.postgresql.util.PSQLException: Unable to bind parameter values for statement.

What improvements can I make?

1
  • It was 2 in the code, made a mistake while typing Commented Jan 12, 2017 at 11:25

1 Answer 1

1

Replace all your code with the following:

File file = new File(...);
String sql = "INSERT INTO hp_xray_results (patient_no,xray_image) VALUES(?,?)";
try (PreparedStatement pstmt = connectDB.prepareStatement(sql);
     FileInputStream fis = new FileInputStream(file)) {
    pstmt.setString(1, jTextField36.getText());
    pstmt.setBinaryStream(2, fis, (int) file.length());
    pstmt.executeUpdate();
} catch (Exception e) {
    ...
}

Documentation links:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.