我在 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);
}
}
}
最佳答案
在你的代码中只有你
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 表的列表。
关于java - 程序运行无异常但不显示表名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11699023/