如何检查数据库中是否存在表或列? [英] How to check if a table or a column exists in a database?
问题描述
我正在尝试使用简单的java代码来检查MySQL数据库中是否存在表和/或列。我应该使用Java代码做检查或者做一个SQL查询字符串并执行它来做检查吗?
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 -
@ 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.
我的DB有很多DB,表和列。我不知道为什么这个程序可以正常工作。
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 !");
}
}
}
推荐答案
要检查表是否存在,您可以使用 DatabaseMetaData :
To check if a table exist you can use DatabaseMetaData in this way :
DatabaseMetaData md = connection.getMetaData();
ResultSet rs = md.getTables(null, null, "table_name", null);
if (rs.next()) {
//Table Exist
}
要检查列是否存在,您可以以类似的方式使用它:
And to check if a column exist you can use it in a similar way :
DatabaseMetaData md = connection.getMetaData();
ResultSet rs = md.getColumns(null, null, "table_name", "column_name");
if (rs.next()) {
//Column in table exist
}
这篇关于如何检查数据库中是否存在表或列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!