首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >程序运行时没有异常,但没有显示任何表名

程序运行时没有异常,但没有显示任何表名
EN

Stack Overflow用户
提问于 2012-07-28 14:58:44
回答 2查看 1.7K关注 0票数 1

我在mysql中有几个数据库,所有的数据库都包含一些带有几列的表。我从一个堆栈溢出答案中得到了下面的代码。答案在:How can I detect a SQL table's existence in Java?

代码给出了输出-

代码语言:javascript
复制
Driver Loaded.
Got Connection.

代码-

代码语言:javascript
复制
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);
}
  }
}
EN

回答 2

Stack Overflow用户

发布于 2012-07-28 20:39:47

在您的代码中,您仅

代码语言:javascript
复制
System.out.println("Driver Loaded.");

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

代码语言:javascript
复制
 Class.forName("com.mysql.jdbc.Driver");
 System.out.println("Driver Loaded.");

我很惊讶这能行得通

代码语言:javascript
复制
conn = DriverManager.getConnection(url, "cowboy", "123456");

,然后您会看到这行代码。

代码语言:javascript
复制
System.out.println("Got Connection.");

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

代码语言:javascript
复制
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.");
      ....
      }
}

设置正确的数据库名称

代码语言:javascript
复制
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表的列表。

票数 2
EN

Stack Overflow用户

发布于 2012-07-28 17:57:02

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

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

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11699023

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档