How to create MySQL table in Python – Step by step tutorial
Hello Python learners, in this Python tutorial I will show you how to create MySQL table in Python. We will see how to create a MySQL Table with Python code.
Before jumping directly to the Python program, I think we need to know a few things:
To work with MySQL in Python we need to have MySQL Connector/Python first.
Create MySQL Table in Python
In MySQL we use MySQL statements to create a table in our database.
Here with the help of the MySQL Connector/Python, we will be able to use all those statements in our Python program.
To work with the connector we need to import the mysql connector in our program.
We need to put this below code at the top of our Python program.
If you get any errors like MySQL connector is not installed then follow this tutorial: How to install MySQL Connector in Python
Python code to create a table in MySQL Database
Start your MySQL server first then use the following Python Code to create a table in your MySQL database.
import mysql.connector db_connection = mysql.connector.connect( host="localhost", user="your_username", passwd="your_password", database="your_db_name" ) my_database = db_connection.cursor() my_database.execute("CREATE TABLE CodeSpeedy (category VARCHAR(255), name VARCHAR(255))")
db_connection is a variable to store all the information needed to create a connection with MySQL.
You can also learn, How to insert data into MySQL Table in Python Programming
To know more about creating a connection follow this tutorial,
my_database.execute("CREATE TABLE CodeSpeedy (category VARCHAR(255), name VARCHAR(255))")
This line will execute the MySQL statement passed as a parameter in execute() function.
If you run this program, it will create a table in your database.
Here CodeSpeedy is the database name. You can choose your preferred database name that is already existing in your database.
If the database is not found then the program will give you an error.