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 data 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.prepareStatement(query); stmt.setString(1, "it's"); ResultSet resultSet = stmt.executeQuery();