2012-07-06 74 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,雖然這可能不是你的問題。

相關問題