How to Create a MySQL Table in Python


If you need to create a table in a MySQL database using Python, then you can do the following.

How to Create a MySQL Table in Python

import mysql.connector

mydb = mysql.connector.connect(
  host = "localhost",
  user = "username",
  password = "YoUrPaSsWoRd",
  database = "your_database"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE TABLE people (name VARCHAR(255), address VARCHAR(255))")

How to Check if a MySQL Table Exists in Python

import mysql.connector

mydb = mysql.connector.connect(
  host = "localhost",
  user = "yourusername",
  password = "YoUrPaSsWoRd",
  database = "your_database"
)

mycursor = mydb.cursor()

mycursor.execute("SHOW TABLES")

for x in mycursor:
  print(x)