我在哪里指定getTables()方法中的数据库名称。

时间:2018-04-30 14:27:38

标签: java sql-server jdbc mssql-jdbc

getTables()方法不会返回数据库中存在的表的任何结果。我认为麻烦的是,我不知道在ip上查看哪个数据库。如何指定getTables()方法应该查找哪个数据库,因为我有多个具有相同表的数据库?

         //concatinating strings for IP to hit
        String ArchiveDB_URL = "jdbc:sqlserver://" + getArchiveIPaddress();


        //  Database credentials
        String USER = "Removed";
        String PASS = "Removed";

        Connection archiveConn = null;
        Statement archiveStmt = null;

        try {

            // Register JDBC driver
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

            // Open a connection   

            archiveConn = DriverManager.getConnection(ArchiveDB_URL, USER, PASS);

            DatabaseMetaData dbm = archiveConn.getMetaData();
            ResultSet rsTBmd = dbm.getTables(null,null, "[myDatabase].[dbo].[myTable]", new String[] {"TABLE"});

            System.out.println(rsTBmd.getString("TABLE_NAME"));

             if (rsTBmd.next()){
               //result sets start at 1 not 0
               int rsTBmdi = 1;  
               while(rsTBmd.next()){
                   System.out.println(rsTBmd.getString(rsTBmdi));
                   rsTBmdi++;
               }
           }

3 个答案:

答案 0 :(得分:2)

getTables的前两个论点是catalogschemaPattern。 “Catalog”是“Database”的另一个名称,因此只需提供数据库名称作为第一个参数:

ResultSet rsTBmd = dbm.getTables("myDatabase", "dbo", "myTable", new String[] {"TABLE"});

请注意,在这种情况下,将名称括在方括号中,即使它们包含空格或“有趣的字符”。

答案 1 :(得分:2)

根据Microsoft,您的JDBC URL看起来像"jdbc:sqlserver://localhost:1433;databaseName=AdventureWorks;user=UserName;password=*****";,从而生成您的代码:

    //  Database credentials
    String USER = "Removed";
    String PASS = "Removed";

    Connection archiveConn = null;
    Statement archiveStmt = null;

    try {

        // Register JDBC driver
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

        // Open a connection   
     //concatinating strings for IP to hit
    String ArchiveDB_URL = "jdbc:sqlserver://" + getArchiveIPaddress() + ";database=myDatabase;username="+USER+";password="+PASS;

        archiveConn = DriverManager.getConnection(ArchiveDB_URL);

        DatabaseMetaData dbm = archiveConn.getMetaData();
        ResultSet rsTBmd = dbm.getTables(null,null, "[myDatabase].[dbo].[myTable]", new String[] {"TABLE"});

        System.out.println(rsTBmd.getString("TABLE_NAME"));

         if (rsTBmd.next()){
           //result sets start at 1 not 0
           int rsTBmdi = 1;  
           while(rsTBmd.next()){
               System.out.println(rsTBmd.getString(rsTBmdi));
               rsTBmdi++;
           }
       }

我希望这会有所帮助......

答案 2 :(得分:1)

尝试在 ArchiveDB_URL

中添加数据库名称
String ArchiveDB_URL = "jdbc:sqlserver://" + getArchiveIPaddress() + "/yourDatabaseNameHere";