I am trying to make simple java code that will check if a table and/or a column exists in a MySQL DB. Should I use Java code to do the checking or make a SQL query string and execute that to do the checking ?
EDIT-
@ aleroot -
I tried using your code as shown below. I don't see any tables or columns when I run the code below. I only see this-
Driver Loaded.
Got Connection.
My DB has got a lot of DB's, tables and columns. I dont know why this program works properly.
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Tester {
static Connection conn;
static Statement st;
public static void main(String[] args) throws Exception {
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);
}
DatabaseMetaData md2 = conn.getMetaData();
ResultSet rsTables = md2.getColumns(null, null, "customers", "name");
if (rsTables.next()) {
System.out.println("Exists !");
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…