Menu Close

Python MySQL Create Table

In this Python MySQL create table tutorial, we are going to learn all about how to create a table after created of the database in MySQL.
In the previous tutorial, we have seen the complete process to create a database in MySQL using Python.

In this guide, we will go through how to create a MySQL table in a database using a python MySQL connector in Python, and also we will see how to show all the created tables.

Make sure you have already installed MySQL connector in your machine using pip as well as create database.

Table of Contents

Python MySQL Create Table

As we know that, MySQL provide “CREATE TABLE” to create new table in MySQL database.

Example:

Here we will create a table named “students“.

import mysql.connector
mydb = mysql.connector.connect(

	host="localhost",
	user="root",
	password="root21",
	database = "demodb",
        port = 3308
	
)

cursor = mydb.cursor()
cursor.execute("CREATE TABLE students ( id INT, name VARCHAR(20), age INT )")
print("Table created successfully...")

Output:

Table created successfully...

Primary Key

You have to always remember, When should also create at least one unique column for each record in the table.

Here we will create a table named “students” with columns id, name, and age where id represents a PRIMARY KEY that increment by 1 whenever a new record inserted into the table.

Example:

import mysql.connector
mydb = mysql.connector.connect(

	host="localhost",
	user="root",
	password="root21",
	database = "demodb",
    port = 3308
	
)

cursor = mydb.cursor()
cursor.execute("CREATE TABLE students ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(20), age INT )")

print("Table created successfully...")

Output:

Table created successfully...

Note:- Above credentials may be different according to your MySQL configuration.
I am showing all the credentials for only testing purposes, It will not working in your case.

Check Table exist:

To check above database create successfully or not, you have to use MySQL “SHOW TABLES” statement.

Example:

import mysql.connector
mydb = mysql.connector.connect(

	host="localhost",
	user="root",
	password="root21",
	database="demodb"
    port = 3308
	
)

cursor = mydb.cursor()
cursor.execute("SHOW TABLES")
for tbl in cursor:
	print(tbl)

Output:

('students',)

Conclusion

In this Python MySQL Create Table tutorial, you have learned all about how to create a table into the database in MySQL using Python.
Python MySQL connector is the best for connecting Python applications to the MySQL database and executes SQL queries. After created of database successfully, you can perform a query on that particular database.

If this article for you, please share and keep visiting for further Python MySQL database tutorials.

Other Topics


More information Python MySQL Create Table:- Click Here

Next Article

Related Posts