首頁  >  問答  >  主體

如何使用Python連接器來檢查MySQL中的表格/資料庫是否已經存在?

<p>所以,我想創建一個程序,它將從用戶那裡獲取關於一切的輸入,即資料庫名稱、表名稱、表結構(列名)、數據,然後對其執行各種添加、刪除、更新等功能。但是我無法檢查用戶輸入的表/資料庫是否已經存在。我嘗試了以下程式碼:</p> <pre class="brush:php;toolbar:false;">def create_table(): table_in_database=input('請輸入要在哪個資料庫中建立此表的名稱:') x=mysql.connect(host=host_name,user=user_name,password=user_password,database=table_in_database) y=x.cursor() if table_in_database in y.fetchall(): name_table=input('請輸入要建立的表的名稱:') if name_table in y.fetchall(): print('表已存在,請嘗試其他名稱或使用現有表') else: table_structure=tuple(input('請輸入表格的結構/行名稱(以逗號分隔):')) y.execute('create table ' name_table '' table_structure '') print('表', name_table, '建立成功') x.commit() else: print('資料庫', table_in_database, '不存在')</pre> <p>但它無法執行y.fetchall(),所以我甚至嘗試使用不同的函數show_database(),它顯示所有資料庫,而不是使用y.fetchall(),但然後出現了NoneType錯誤。是否有任何方法可以檢查表/資料庫是否存在? </p>
P粉242535777P粉242535777396 天前460

全部回覆(1)我來回復

  • P粉757432491

    P粉7574324912023-08-29 11:40:21

    如果您連接到一個資料庫並執行查詢 SHOW TABLES;,它將傳回該資料庫中所有資料表的清單。
    您可以使用條件精確搜尋:

    SHOW tables 
    WHERE Tables_in_test ='triangle';
    +----------------+
    | Tables_in_test |
    +----------------+
    | triangle       |
    +----------------+

    您需要修改列的名稱以符合您的資料庫。

    Tables_in_[database_name]

    回覆
    0
  • 取消回覆