0

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

2
  • What do you mean by database name? Are you referring to the MS-SQL Server instance name or some other name? Commented Aug 19, 2011 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 Commented Aug 19, 2011 at 3:31

2 Answers 2

4

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));
Sign up to request clarification or add additional context in comments.

Comments

1
public List<String> getServerDataBaseNameList() {
    List<String> dataBaseNameList = new ArrayList<String>();
    try {
        ResultSet resultSet = con.getConnectionMetaData().getCatalogs();
        if (resultSet == null) {
            return null;
        }
        while (resultSet.next()) {
            dataBaseNameList.add(resultSet.getString(1));
        }
        return dataBaseNameList;
    } catch (SQLException e) {
        logger.error("Error during execute select query for fetch server database name");
    }
    return null;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.