如何通过Hibernate获取我连接的数据库名称? [英] How can I get the database name I am connected to through Hibernate?

查看:369
本文介绍了如何通过Hibernate获取我连接的数据库名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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?

推荐答案

您可以:


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

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

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

Obtain a JDBC Connection from 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.

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

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

这篇关于如何通过Hibernate获取我连接的数据库名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆