程序运行无例外,但没有显示表名

我在mysql中有一些DB,所有这些都包含一些带有几列的表。 我从堆栈溢出答案中得到了下面的代码。 答案是: 我如何在Java中检测SQL表的存在?

代码给出输出 –

Driver Loaded. Got Connection. 

码-

 import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class Main { public static void main(String[] args) throws Exception { DatabaseMetaData md = conn.getMetaData(); ResultSet rs = md.getTables(null, null, "%", null); while (rs.next()) { System.out.println(rs.getString(3)); } } static Connection conn; static Statement st; static { try { // Step 1: Load the JDBC driver. System.out.println("Driver Loaded."); // Step 2: Establish the connection to the database. String url = "jdbc:mysql://localhost:3306/"; conn = DriverManager.getConnection(url, "cowboy", "123456"); System.out.println("Got Connection."); st = conn.createStatement(); } catch (Exception e) { System.err.println("Got an exception! "); e.printStackTrace(); System.exit(0); } } } 

在你的代码中你只

 System.out.println("Driver Loaded."); 

这还不够。 你必须先加载驱动程序!

  Class.forName("com.mysql.jdbc.Driver"); System.out.println("Driver Loaded."); 

我很惊讶这是有效的

 conn = DriverManager.getConnection(url, "cowboy", "123456"); 

并且你来到这行代码。

 System.out.println("Got Connection."); 

使用以下代码,它将会运行,但您将无法获得表列表

 static { try { // Step 1: Load the JDBC driver. Class.forName("com.mysql.jdbc.Driver"); System.out.println("Driver Loaded."); // Step 2: Establish the connection to the database. String url = "jdbc:mysql://localhost"; conn = DriverManager.getConnection(url,"user","passw"); System.out.println("Got Connection."); .... } } 

正确设置数据库名称

 static { try { // Step 1: Load the JDBC driver. Class.forName("com.mysql.jdbc.Driver"); System.out.println("Driver Loaded."); // Step 2: Establish the connection to the database. String url = "jdbc:mysql://localhost/myDataBase"; conn = DriverManager.getConnection(url,"user","passw"); System.out.println("Got Connection."); .... } } 

你可以看到myDataBase表的列表。

此代码用于显示特定数据库的表,而不是所有DB的所有表。 您没有在url String中指定任何数据库,因此无需显示任何内容。

如果仔细查看用于回答链接问题的链接,可以看到String url = "jdbc:hsqldb:data/tutorial"; 所以你必须先连接到数据库。

PS:如果在jdbc4之前使用驱动程序,则可能必须加载驱动程序,使用: Class.forName("com.mysql.jdbc.Driver"); 并确保驱动程序在类路径中可用。