To check if a table exists in a MySQL database using Python, you can use the `
SHOW TABLES
` statement to retrieve a list of all the tables in the database and then check if the specified table is in the list.
Here's an example Python program that checks if a table exists in a
MySQL database :
Example :
import mysql.connector
# Create a connection to the MySQL server
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
# Create a cursor object to execute SQL statements
mycursor = mydb.cursor()
# Check if a table exists
mycursor.execute("SHOW TABLES")
tables = mycursor.fetchall()
table_name = "customers"
if (table_name,) in tables:
print("The table exists.")
else:
print("The table does not exist.")​