Search code examples
javastringpostgresqluuidguid

How to convert a String to a GUID


I need to convert a String to a GUID, there are lots of tutorials online about converting one to a UUID but not to a GUID. I am working in Java.

When I use a UUID, I get the following error:

ERROR: operator does not exist: character varying = uuid
Hint: No operator matches the given name and argument types. You might need to add explicit type casts.

I have tried using help from the following question but Guid doesn't seem to be a type in java and the constructor for GUID doesn't take any arguments:

How to try convert a string to a Guid


Solution

  • Assuming your column is defined as uuid in Postgres, you can use java.util.UUID for that.

    Something like:

    java.util.UUID id = UUID.fromString("...."); 
    PreparedStatement pstmt = connection.prepareStatement("select * from some_table where id = ?");
    pstmt.setObject(1, id);
    ResultSet rs = pstmt.executeQuery();
    while (rs.next()) {
      ... do something 
    }