Home  >  Q&A  >  body text

How to use Python connector to check if a table/database in MySQL already exists?

<p>So, I want to create a program that will take input from the user about everything, i.e. database name, table name, table structure (column names), data and then perform various add, delete, update on it and other functions. But I can't check if the table/database entered by the user already exists. I tried the following code: </p> <pre class="brush:php;toolbar:false;">def create_table(): table_in_database=input('Please enter the name of the database in which you want to create this table:') 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('Please enter the name of the table to be created:') if name_table in y.fetchall(): print('Table already exists, please try another name or use an existing table') else: table_structure=tuple(input('Please enter the structure/row names of the table (separated by commas):')) y.execute('create table ' name_table '' table_structure '') print('table', name_table, 'created successfully') x.commit() else: print('database', table_in_database, 'does not exist')</pre> <p>But it fails to do y.fetchall(), so I even tried using a different function show_database() which shows all databases instead of using y.fetchall(), but then I got a NoneType error. Is there any way to check if the table/database exists? </p>
P粉242535777P粉242535777396 days ago458

reply all(1)I'll reply

  • P粉757432491

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

    If you connect to a database and run the query SHOW TABLES;, it will return a list of all tables in that database.
    You can use criteria to search more precisely:

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

    You need to modify the column names to match your database.

    Tables_in_[database_name]

    reply
    0
  • Cancelreply