Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...