2012-07-06 75 views
4

我现在用的是这样的:如何使用MySQL检查数据库中是否已经存在表?

dbResult = dbStatement.executeQuery("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '[e2]' AND table_name = '[emp101_messages]'"); 
while(dbResult.next()) 
{ 
    int value = -1; 
    value= dbResult.getInt(1); 
    System.out.println(value + " table count"); 
} 

是检查这个正确的方法,如果数据库表中存在?

回答

5
SELECT table_name 
FROM information_schema.tables 
WHERE table_schema = 'dbname' 
    AND table_name = 'my_tablename'; 

+----------------------+ 
| table_name   | 
+----------------------+ 
| my_tablename | 
+----------------------+ 

由于大部分选项已经提供。请看看这是否有帮助。

+0

谢谢你..它的工作.. – 2012-07-06 07:24:07

+0

很高兴它帮助你。 – 2012-07-06 07:26:46

2

使用此:

SHOW [FULL] TABLES [{FROM | IN} db_name] 
    [LIKE 'pattern' | WHERE expr] 

正如有时你不访问元数据。

1

如果你只想检查,如果1,2或几个表存在,为什么不使用:mysql> show tables like "test1";

1

您还可以使用:

SHOW TABLES LIKE "emp101_messages"; 

我认为这是更有效的。

1

这是一个正确的方法。 (只是被表格名称周围的“[]”大括号所困惑 - 这些很可能不是实际名称的一部分,所以需要删除)

此外,它是一种有效的方法:由于您提供常数都table_schema以及为table_name,你因此利用INFORMATION_SCHEMA optimizations,在该表中没有连开:

explain select count(*) from information_schema.tables where table_schema='world' and table_name='City'; 
+----+-------------+--------+------+---------------+-------------------------+---------+------+------+---------------------------------------------------+ 
| id | select_type | table | type | possible_keys | key      | key_len | ref | rows | Extra            | 
+----+-------------+--------+------+---------------+-------------------------+---------+------+------+---------------------------------------------------+ 
| 1 | SIMPLE  | tables | ALL | NULL   | TABLE_SCHEMA,TABLE_NAME | NULL | NULL | NULL | Using where; Skip_open_table; Scanned 0 databases | 
+----+-------------+--------+------+---------------+-------------------------+---------+------+------+---------------------------------------------------+ 

提供的“SHOW TABLES”的解决方案是好的,太 - 和几乎一样就像Java/Python /无论代码如何。其结果是有效的ResultSet:

SHOW TABLES FROM world LIKE 'City'; 
+------------------------+ 
| Tables_in_world (City) | 
+------------------------+ 
| City     | 
+------------------------+ 

但只完成了故事:它不是标准的SQL语法 - 如果你正在使用像某些种类的ORM一些框架,你可能并不总是能够用这种类型的查询来解决问题(因为我记得EJB3不会让你这样做)。

此外,它很难解析服务器端,请参阅:Reading results of SHOW statements, on server side,虽然这可能不是你的问题。

相关问题