Python MySQL – Create Table
To create a table in MySQL from Python, we run the SQL CREATE TABLE command with the cursor. Before this, you should know how to connect Python to MySQL.
Create the users table
We create a table named users in the student database with four columns.
| Column | Type | Meaning |
|---|---|---|
| id | INT AUTO_INCREMENT PRIMARY KEY | Unique number, MySQL fills it automatically |
| name | VARCHAR(100) | Name of the user, required |
| mobile | VARCHAR(15) | Mobile number as text |
| VARCHAR(100) | Email address |
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="student"
)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
mobile VARCHAR(15),
email VARCHAR(100)
)
""")
print("Table users is ready")
cursor.close()
conn.close()
Output of the above program is
Table users is ready
We used IF NOT EXISTS, so running the program again does not give an error if the table is already there. Without it MySQL raises an error that the table exists.
Check that the table exists
Use the SHOW TABLES command and loop over the cursor.
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="student"
)
cursor = conn.cursor()
cursor.execute("SHOW TABLES")
for table in cursor:
print(table)
cursor.close()
conn.close()
Output of the above program is
('users',)
Note:
Each row from the cursor comes as a tuple. That is why the table name is shown in brackets with a comma.
Summary
- Run
CREATE TABLEwithcursor.execute(). - Use
IF NOT EXISTSto make the program safe to run again. - Use
SHOW TABLESto check your tables. - Next: insert data into the table.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |