我在mysql中有几个数据库,所有的数据库都包含一些带有几列的表。我从一个堆栈溢出答案中得到了下面的代码。答案在: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);
}
}
}发布于 2012-07-28 20:39:47
在您的代码中,您仅
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-28 17:57:02
此代码用于显示特定数据库的表,而不是所有DB的所有表。您没有在url字符串中指定任何数据库,因此没有显示任何内容。
如果您仔细查看用于回答链接问题的link,您可以看到String url = "jdbc:hsqldb:data/tutorial";,因此您必须首先连接到数据库。
PS :如果您在使用jdbc4之前使用driver,则可能需要加载驱动程序,请使用:Class.forName("com.mysql.jdbc.Driver");,并确保驱动程序在类路径中可用。
https://stackoverflow.com/questions/11699023
复制相似问题