WJun
WJun

Reputation: 3

Java updating Image to Mysql : result Null(insert, select image works fine)

I am trying to upload image to mysql through swing GUI application.

What I am having trouble is updating image(blob). Insert and select just works fine and same updating query with other int, String fields also work fine.

try {
                  File sel = new File(path);
                  String a = sel.toURI().toString();
                  InputStream FIS = new FileInputStream(sel);

                  String insert_sql = "INSERT INTO cal (user_id, time, image) "
                        + "VALUES(?,?,?)"
                        + "ON DUPLICATE KEY UPDATE image = ?;"; // 만약 key가 있다면 update.
                  PreparedStatement preparedStmt = conn.prepareStatement(insert_sql);
                  preparedStmt.setInt(1, user_id);
                  preparedStmt.setString(2, date);
                  preparedStmt.setBlob(3, FIS);
                  preparedStmt.setBlob(4, FIS);
                  preparedStmt.execute();
               } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
               } catch (SQLException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
               }
}

If there is no same Key, then inserting image works just fine. However, if there is a row with same ID whether "image" column is null or not null then it gives null output. Moreover, As i mentioned at the top, this query works well with other String, Integer fields.

Thanks in advance for your help.

Upvotes: 0

Views: 29

Answers (1)

ControlAltDel
ControlAltDel

Reputation: 35011

The answer is to use mysqls "on duplicate key update"

insert into mytable (x,y,z) value (a,b,c) on duplicate key update;

Upvotes: 1

Related Questions