JDBC/Java - 如何检查数据库中是否存在表和列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11729828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JDBC/Java - How to check if a table and also a column exist in a database?
提问by sweet dreams
I am using MySql, jdbc and java for my code. I want the code to check if:
我的代码使用的是 MySql、jdbc 和 java。我希望代码检查是否:
1- A table exists in a particular database. 2- A column exists in a particular table of a particular database.
1- 表存在于特定数据库中。2- 列存在于特定数据库的特定表中。
Can you tell me how to do this ?
你能告诉我怎么做吗?
回答by anttix
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! 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=20913you should either upgrade or use database name as the first argument to getTables
注意!如果未列出任何表,则您使用的是具有以下错误的旧版 MySQL JDBC 驱动程序http://bugs.mysql.com/bug.php?id=20913您应该升级或使用数据库名称作为第一个参数获取表
回答by Samson
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'
回答by JB Nizet
Use Connection.getMetaData(), and use the returned object to get the catalogs, schemas, tables and columns.
使用Connection.getMetaData(),并使用返回的对象来获取目录、模式、表和列。
回答by Andre
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");
}