1

我在 mysql 中有一些数据库,它们都包含一些带有几列的表。我从堆栈溢出答案中得到了下面的代码。答案是: 如何在 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);
}
  }
}
4

2 回答 2

2

在您的代码中,您只

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 表的列表。

于 2012-07-28T12:39:47.023 回答
1

This code is used to display the tables of a specific database, not all tables of all DB. You don't specify any database in your url String so there is nothing to display.

If you look carefully at the link used to answer the linked question, you can see String url = "jdbc:hsqldb:data/tutorial"; So you have to be connected to a database first.

PS : You may have to load the driver if you use driver prior to jdbc4, use : Class.forName("com.mysql.jdbc.Driver"); and be sure the driver is available in the classpath.

于 2012-07-28T09:57:01.730 回答