简体   繁体   English

如何使用 JDBC 引用/转义诸如列名之类的标识符?

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

Different database servers use different ways to quote and escape identifiers.不同的数据库服务器使用不同的方式来引用和转义标识符。

Eg "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.例如,"foo bar" vs `foo bar` vs [foo bar],或"10""" vs "10\\"",或者像 FooBar 或数组这样的标识符需要为某些数据库引用,但不需要为其他数据库引用。

Is there any API method that performs the quoting/escaping correctly for a given database connection?是否有任何 API 方法可以为给定的数据库连接正确执行引用/转义? Or any alternative solution?或者任何替代解决方案?

Have a look at看看

DatabaseMetaData.getIdentifierQuoteString()

I never used it but it sounds good :-)我从未使用过它,但听起来不错:-)

getExtraNameCharacters() could also be of some help getExtraNameCharacters()也可能有所帮助

Since Java 9, the Statement interface provides various methods for engine-specific quoting:从 Java 9 开始, Statement接口为引擎特定的引用提供了各种方法:

  • enquoteIdentifier for SQL identifiers (eg schema, table, column names)用于 SQL 标识符的enquoteIdentifier (例如模式、表、列名)
  • enquoteLiteral for string literals (eg char, varchar, text literals) enquoteLiteral用于字符串文字(例如 char、varchar、文本文字)
  • enquoteNCharLiteral for National Character Set literals enquoteNCharLiteral用于国家字符集文字
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 (ie for values in CRUD queries), use prepared statements instead.但是,只要有可能(即对于 CRUD 查询中的值),请改用准备好的语句。

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();

I think the answer to your question is that if you are writing a database neutral application using JDBC, then you need to use database neutral names, and not things that require special escaping per database vendor.我认为您的问题的答案是,如果您正在使用 JDBC 编写数据库中立应用程序,那么您需要使用数据库中立名称,而不是需要每个数据库供应商进行特殊转义的东西。

There is nothing I know of in the JDBC which supports that.我不知道在 JDBC 中支持它。 A ORM product will deal with such things. ORM 产品会处理这些事情。

Edit: If you are writing an ORM, then I would think need a seperate SQL generation class for each supported database, just to handle the various syntax involved, so you would have to write that.编辑:如果您正在编写 ORM,那么我认为每个受支持的数据库都需要一个单独的 SQL 生成类,以处理所涉及的各种语法,因此您必须编写它。 You can certainly look at the source code of the various open source ORM's out there and see how they handle it.您当然可以查看各种开源 ORM 的源代码,看看它们是如何处理的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM