In this example we will show how to check if a table exists by listing all tables in your database in Python.
Source Code
import mysql.connector
# connect to server
mydb = mysql.connector.connect(
host="localhost",
port=3306,
user="yourusername",
password="yourpassword",
db="mydatabase"
)
# get a cursor
mycursor = mydb.cursor()
# delete if the table exists
mycursor.execute("SHOW TABLES")
for item in mycursor:
print(item)
# close the connection
mydb.close()
Output:
('student',)