程序运行无例外,但没有显示表名 [英] Program runs without exception but shows no table names

查看:131
本文介绍了程序运行无例外,但没有显示表名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a few DB's in mysql and all of them contain some tables with a few columns. I got the code below from a stack overflow answer. The answer is at: How can I detect a SQL table's existence in Java?

代码给出输出 -

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.");

使用以下代码,它会去,但你不会得到一个表列表

with the following code, it will go, but you will not get a list of tables

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

and you can see a list of your myDataBase tables.

这篇关于程序运行无例外,但没有显示表名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆