简体   繁体   English

JDBC / Java - 如何检查数据库中是否存在表和列?

[英]JDBC/Java - How to check if a table and also a column exist in a database?

I am using MySql, jdbc and java for my code. 我正在使用MySql,jdbc和java代码。 I want the code to check if: 我希望代码检查是否:

1- A table exists in a particular database. 1-表存在于特定数据库中。 2- A column exists in a particular table of a particular database. 2-列存在于特定数据库的特定表中。

Can you tell me how to do this ? 你能告诉我怎么做吗?

A correct way is to use JDBC MetaData 正确的方法是使用JDBC MetaData

Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
DatabaseMetaData metadata = connection.getMetaData();
ResultSet resultSet;
resultSet = metadata.getTables(null, null, "tablename", null);
if(resultSet.next())
    // Table exists

resultSet = metadata.getColumns(null, null, "tablename", "columnName");
if(resultSet.next())
    // Column exists

To debug your code it might be a good idea to try to fetch all table names first and print them out like this: 要调试代码,最好先尝试获取所有表名,然后将其打印出来,如下所示:

resultSet = metadata.getTables(null, null, "%", null);
while(resultSet.next())
    System.out.println(resultSet.getString("TABLE_NAME"));

NB! NB! If no tables are listed, you are using an older version of MySQL JDBC driver with the following bug http://bugs.mysql.com/bug.php?id=20913 you should either upgrade or use database name as the first argument to getTables 如果未列出任何表,则使用旧版本的MySQL JDBC驱动程序,并出现以下错误http://bugs.mysql.com/bug.php?id=20913您应该升级或使用数据库名称作为第一个参数的getTables

Look for the table: 寻找表格:

SELECT COUNT(*)
FROM information_schema.tables 
WHERE table_schema = 'db_name' 
AND table_name = 'table_name';

and if it exists then look for the column: 如果它存在,那么查找列:

SELECT * 
FROM information_schema.COLUMNS 
WHERE 
    TABLE_SCHEMA = 'db_name' 
AND TABLE_NAME = 'table_name' 
AND COLUMN_NAME = 'column_name'

使用Connection.getMetaData() ,并使用返回的对象来获取目录,模式,表和列。

 Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
 DatabaseMetaData metadata = connection.getMetaData();
 ResultSet resultSet;
 resultSet = metadata.getTables(null, null, "tablename", null);
 if(resultSet!=null){
   // next() checks if the next table exists ...
      System.out.println("Table exists");
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM