How to quote/escape identifiers such as column names with JDBC?

前端 未结 3 1012
走了就别回头了
走了就别回头了 2021-01-17 16:29

Different database servers use different ways to quote and escape identifiers.

E.g. \"foo bar\" vs `foo bar` vs [foo bar], or \"10\"\"\" vs \"10\\\"\", or identifier

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-17 17:09

    Since Java 9, the Statement interface provides various methods for engine-specific quoting:

    • enquoteIdentifier for SQL identifiers (e.g. schema, table, column names)
    • enquoteLiteral for string literals (e.g. char, varchar, text literals)
    • enquoteNCharLiteral for National Character Set literals
    Statement stmt = connection.createStatement();
    String query = String.format(
            "SELECT id FROM %s WHERE name = %s",
            stmt.enquoteIdentifier("table", false),
            stmt.enquoteLiteral("it's"));
    ResultSet resultSet = stmt.executeQuery(query);
    

    However, whenever possible (i.e. for values in CRUD queries), use prepared statements instead.

    Statement stmtFormat = connection.createStatement();
    String query = String.format(
            "SELECT id FROM %s WHERE name = ?", 
            stmtFormat.enquoteIdentifier("table", false);
    PreparedStatement stmt = connection.createPreparedStatement(query);
    stmt.setString(1, "it's");
    ResultSet resultSet = stmt.executeQuery();
    

提交回复
热议问题