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 identifiers such as FooBar or array need to be quoted for some databases but not for others.
Is there any API method that performs the quoting/escaping correctly for a given database connection? Or any alternative solution?
If the table names and the column names are shown in lowercase letters this means they are delimited and quotation marks need to be used for the table names and the column names when executing SQL queries against the Oracle database.
Both these are keywords in SQL. The trick here is to type the column names inside the square brackets '[]' so that they are not read as a Reserved Word by the compiler.
Backticks are used in MySQL to select columns and tables from your MySQL source. In the example below we are calling to the table titled Album and the column Title . Using backticks we are signifying that those are the column and table names. SELECT `Album`.
To escape reserved keywords in SQL SELECT statements and in queries on views, enclose them in double quotes ('').
Have a look at
DatabaseMetaData.getIdentifierQuoteString()
I never used it but it sounds good :-)
getExtraNameCharacters()
could also be of some help
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 literalsStatement 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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With