java 如何从Java中的数据源名称获取sqlserver数据库名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7116517/
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-30 18:41:42  来源:igfitidea点击:

How to get sqlserver database name from datasource name in Java

javadatabasesqldatasource

提问by Even

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!

如标题所述,我想在 sqlserver 中获取数据库名称,我知道的所有信息是数据源名称、登录名/密码以获取 Connection 对象,请显示一些有关如何正确检索数据库名称的指针,在 java 中,谢谢!

Even

甚至

回答by adatapost

Obtain an instance of java.sql.DatabaseMetaDatafrom the connection object.

java.sql.DatabaseMetaData从连接对象中获取 的实例。

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

可以通过getCatalogs()getSchemas()方法获取数据库名称(取决于JDBC驱动程序的供应商)。

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

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

或使用Connection.getCatalog()Connection.getSchema()方法。

In case if you are interested to get host nameor ip addressof the Oracle database server.

如果您有兴趣获得host nameip addressOracle 数据库服务器。

 ResultSet rs=st.executeQuery("select UTL_INADDR.GET_HOST_NAME from dual");
 while(rs.next())
    System.out.println(rs.getString(1));

回答by M2E67

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;
}