Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

jdbc

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?

like image 719
aditsu quit because SE is EVIL Avatar asked Jan 10 '10 19:01

aditsu quit because SE is EVIL


People also ask

Do column names need quotes in SQL?

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.

How do you handle SQL column names that look like SQL keywords?

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.

How to use Backticks in SQL?

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`.

How do I escape a reserved word in SQL Server?

To escape reserved keywords in SQL SELECT statements and in queries on views, enclose them in double quotes ('').


2 Answers

Have a look at

DatabaseMetaData.getIdentifierQuoteString()

I never used it but it sounds good :-)

getExtraNameCharacters() could also be of some help

like image 69
user85421 Avatar answered Nov 13 '22 03:11

user85421


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();
like image 23
OrangeDog Avatar answered Nov 13 '22 03:11

OrangeDog