java 如何获取我通过 Hibernate 连接的数据库名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/821466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 13:56:02  来源:igfitidea点击:

How can I get the database name I am connected to through Hibernate?

javasql-serverhibernate

提问by Ascalonian

I am trying to get the name of the database I am connected to in SQL Server. I tried doing:

我正在尝试获取我在 SQL Server 中连接的数据库的名称。我试着做:

Query query = session.createQuery("SELECT db_name()");
List<String> dbNames = query.list();

However, I got the following error:

但是,我收到以下错误:

[ERROR PARSER:35] *** ERROR: <AST>:0:0: unexpected end of subtree
Exception in thread "main" java.lang.IllegalStateException: No data type for node: org.hibernate.hql.ast.MethodNode 
 \-[METHOD_CALL] MethodNode: '('
    +-[METHOD_NAME] IdentNode: 'db_name' {originalText=db_name}
    \-[EXPR_LIST] SqlNode: 'exprList'

How can I get the name of the database I am connected to?

如何获取我连接的数据库的名称?

回答by javashlook

You can either:

您可以:

  1. Create a native SQL query, with session.createSQLQuery(...). You can extract a single row of results with uniqueResult().

  2. Obtain a JDBC Connectionfrom the Session, and extract the connection string from the database meta-data. For SQL Server, I believe you'll need to parse connection.getMetaData().getURL()in order to extract the actual database name.

  1. 创建本机 SQL 查询,使用session.createSQLQuery(...). 您可以使用 提取单行结果uniqueResult()

  2. Connection从 中获取 JDBC Session,并从数据库元数据中提取连接字符串。对于 SQL Server,我相信您需要进行解析connection.getMetaData().getURL()才能提取实际的数据库名称。

Note that Session.connection()is considered deprecated, and you're supposed to use Session.doWork().

请注意,这Session.connection()被视为已弃用,您应该使用Session.doWork().

回答by Nuno Furtado

AFAIK you cannot call NAtive database functions that way. Try using a Native Query instead of a simple query : http://www.roseindia.net/hibernate/hibernate-native-sql.shtml

AFAIK 您不能以这种方式调用本机数据库函数。尝试使用本机查询而不是简单查询:http: //www.roseindia.net/hibernate/hibernate-native-sql.shtml