Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

As specified in the title, I want to get the database name in sqlserver, all info I know is datasource name, login name/password to get the Connection object, please show some pointers on how to retrieve the database name correctly, in java, thanks!

Even

share|improve this question
    
Please consider accepting answers. –  Kal Aug 19 '11 at 3:06
    
What do you mean by database name? Are you referring to the MS-SQL Server instance name or some other name? –  Vineet Reynolds Aug 19 '11 at 3:14
    
I meant database instance name, as shown below:Microsoft SQL Server ODBC Driver Version 06.00.6002 Data Source Name: SM9 Data Source Description: Server: *** Database: SM9 Data Encryption: No –  Even Aug 19 '11 at 3:31

2 Answers 2

up vote 0 down vote accepted

Obtain an instance of java.sql.DatabaseMetaData from the connection object.

The names of database can be obtained via getCatalogs() or getSchemas() method (It depends upon the vendor of JDBC driver).

ResultSet rs=cn.getMetaData().getSchemas();
while(rs.next()) {
   System.out.println(rs.getString(1));
}

Or use Connection.getCatalog() or Connection.getSchema() method.

In case if you are interested to get host name or ip address of the Oracle database server.

 ResultSet rs=st.executeQuery("select UTL_INADDR.GET_HOST_NAME from dual");
 while(rs.next())
    System.out.println(rs.getString(1));
share|improve this answer
    
Yeah, seems api for this DatabaseMetaData is pretty rich, however, what is the right one for database name?? Could kindly be more specific, thank you~~ –  Even Aug 19 '11 at 3:33

You can use :

 con.getClientInfo()

to get all the info/properties of your database and then point to the specific property of interest.As in your case con.getClientInfo("database") should do the work. This works for me in sql server.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.