Python MySQL - Create and List Table
Now we will learn how to create tables in any MySQL database in Python and we will also see how to check if a table already exists or not by listing down all the tables in a database using Python.
Python MySQL - Create Table
Basically, to store information in the MySQL database there is a need to create the tables. It is also required to select our database first and then create tables inside that database.
At the time of creating the connection, you can also specify the name of your database, like given below:
import mysql.connector
db = mysql.connector.connect(
host = "localhost",
user = "yourusername",
password = "yourpassword",
database = "studytonight"
)
If the above code is executed without any errors then it means you have successfully connected to the database named studytonight.
SQL Query to Create Table
To create a table in the selected database the following statement will be used. Let us see the syntax:
CREATE TABLE table_name;
Let us create a table named students in the specified database, that is studytonight
In the table students we will have the following fields: name, rollno, branch, and address.
#for our convenience we will import mysql.connector as mysql
import mysql.connector as mysql
db = mysql.connect(
host = "localhost",
user = "yourusername",
passwd = "yourpassword",
database="studytonight"
)
cursor = db.cursor()
cursor.execute("CREATE TABLE students (name VARCHAR(255), rollno INTEGER(100), branch VARCHAR(255), address VARCHAR(255))")
If this code executes without any error then it means the table has been created successfully.
Now, If you want to check the existing tables in the database then you can use the SHOW TABLES
SQL statement.
List existing Tables in a Database
Now as we have created a table in our database. Let us check the tables that exist in our database. Use the code given below:
#for our convenience we will import mysql.connector as mysql
import mysql.connector as mysql
db = mysql.connect(
host = "localhost",
user = "yourusername",
passwd = "yourpassword",
database="studytonight"
)
cursor = db.cursor()
## getting all the tables which are present in 'datacamp' database
cursor.execute("SHOW TABLES")
tables = cursor.fetchall() ## it returns list of tables present in the database
## showing all the tables one by one
for table in tables:
print(table)
The output of the above code is as follows
('students',)
Python MySQL - Table with Primary Key
As we had created a table named students in our database, in which we will store student data and fetch it whenever required. But while fetching data, we might find students with same name and that can lead to wrong data getting fetched, or cause some confusion.
So to uniquely identify each record in a table we can use Primary Key in our tables. Let us see first what is a Primary key?
What is Primary Key?
A primary key is an attribute to make a column or a set of columns accept only unique values. With the help of the primary key, one can find each row uniquely in the table.
Watch this video to learn about DBMS Keys - DBMS Keys Explained with Examples
Thus in order to identify each row uniquely with a number starting from 1. We will use the syntax as follows:
INT AUTO_INCREMENT PRIMARY KEY
Using the above code with any column, we can make its value as auto increment, which means the database will automatically add an incremented value even if you do not insert any value for that column while inserting a new row of data to your table.
Add Primary Key during Table creation
Let us see how to add a primary key at the time of table creation. The code snippet for the same is given below:
import mysql.connector as mysql
db = mysql.connect(
host = "localhost",
user = "yourusername",
passwd = "yourpassword",
database = "studytonight"
)
cursor = db.cursor()
## creating the 'students' table with the 'PRIMARY KEY'
cursor.execute("CREATE TABLE students (name VARCHAR(255), rollno INTEGER(100) NOT NULL AUTO_INCREMENT PRIMARY KEY, branch VARCHAR(255), address VARCHAR(255))")
If the above code runs without an error then it means you have successfully created a table named "students" with the column rollno as primary key.
Python MySQL - Describe the Table
We can use the below python code to describe any table to see what all columns it has and all the meta information about the table and all its columns.
import mysql.connector as mysql
db = mysql.connect(
host = "localhost",
user = "yourusername",
passwd = "yourpassword",
database = "studytonight"
)
cursor = db.cursor()
cursor.execute("DESC students")
print(cursor.fetchall())
The output will be:
[('name', 'varchar(255)', 'YES', '', None, ''), ('rollno', 'int', 'NO', 'PRI', None, 'auto_increment'), ('branch', 'varchar(255)', 'YES', '', None, ''), ('address', 'varchar(255)', 'YES', '', None, '')]
Add Primary Key to Existing Table
Now in this example, we will assume that rollno column does not exist in our student table. So we will learn how to add a column to be used as primary key in an existing table.
Let us see how to create a primary key on an existing table. The code snippet for the same is given below:
import mysql.connector as mysql
db = mysql.connect(
host = "localhost",
user = "root",
passwd = "himaniroot@99",
database = "studytonight"
)
cursor = db.cursor()
## We are going to add rollno field with primary key in table students
cursor.execute("ALTER TABLE students ADD COLUMN rollno INT AUTO_INCREMENT PRIMARY KEY")
print(cursor.fetchall())
In the above code we have used the SQL Alter Query to add a new column to an existing table. You can use the describe table query to see the new added column.
[('name', 'varchar(255)', 'YES', '', None, ''), ('branch', 'varchar(255)', 'YES', '', None, ''), ('address', 'varchar(255)', 'YES', '', None, ''), ('rollno', 'int', 'NO', 'PRI', None, 'auto_increment')]
So in this tutorial we have covered everything related to creating a new MySQL table in python. We covered how to alter a table, how to list down all the tables in a database, and how to define a column as a primary key.