Home > Database > Mysql Tutorial > How to Use PostgreSQL JSONB Operators (`?`, `?|`, `?&`, `/`) with JDBC Prepared Statements?

How to Use PostgreSQL JSONB Operators (`?`, `?|`, `?&`, `/`) with JDBC Prepared Statements?

Susan Sarandon
Release: 2024-12-24 03:18:15
Original
889 people have browsed it

How to Use PostgreSQL JSONB Operators (`?`, `?|`, `?&`, `/`) with JDBC Prepared Statements?

Using PostgreSQL JSON(B) Operators with Question Marks ("?") in JDBC

PostgreSQL offers various operators, including ?/?|/ and ?&, which facilitate JSON handling. However, the PostgreSQL JDBC driver encounters difficulties parsing SQL strings containing these operators. This article explores two workarounds for utilizing these operators in JDBC.

Solution 1: Static Statements

One approach is to employ static statements instead of prepared statements. While this method eliminates prepared statement benefits, it effectively handles operators.

try (Statement s = c.createStatement();
     ResultSet rs = s.executeQuery("select '{}'::jsonb ?| array['a', 'b']")) {
     ...
}
Copy after login

Solution 2: Function Substitution

Operators are mere syntactic constructs that correspond to functions in the pg_catalog. By identifying these functions, you can directly invoke them without using operators. This method may impact indexing efficiency.

To find the corresponding function, execute the following SQL query:

SELECT 
  oprname, 
  oprcode || '(' || format_type(oprleft,  NULL::integer) || ', ' 
                 || format_type(oprright, NULL::integer) || ')' AS function
FROM pg_operator 
WHERE oprname = '?|';
Copy after login

The resulting function, "jsonb_exists_any(jsonb, text[])", can be used in prepared statements:

try (PreparedStatement s = c.prepareStatement(
         "select jsonb_exists_any('{}'::jsonb, array['a', 'b']");
     ResultSet rs = s.executeQuery()) {
     ...
}
Copy after login

The above is the detailed content of How to Use PostgreSQL JSONB Operators (`?`, `?|`, `?&`, `/`) with JDBC Prepared Statements?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template