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>