Reputation: 2134
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?
The code gives the output-
Driver Loaded.
Got Connection.
Code-
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);
}
}
}
Upvotes: 1
Views: 1877
Reputation: 20065
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.
Upvotes: 1
Reputation: 11958
In your Code you only
System.out.println("Driver Loaded.");
That's not enough. You have to load the driver first!
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver Loaded.");
I'm surprised that this works
conn = DriverManager.getConnection(url, "cowboy", "123456");
and that you come to this line of code.
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.");
....
}
}
set the database name correctly
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.");
....
}
}
and you can see a list of your myDataBase tables.
Upvotes: 2