Mysql Create Table in Python
MySQL Create Table in Python
You can create a MySQL table in Python using the mysql-connector-python library.
1. Install MySQL Connector
If you haven’t installed the MySQL connector, install it using:
pip install mysql-connector-python2. Connect to MySQL Database
Before creating a table, establish a connection to your MySQL database.
import mysql.connector# Connect to MySQL server and select databaseconn = mysql.connector.connect( host="localhost", user="root", password="password", database="mydatabase" # Change to your database name)# Create a cursor objectcursor = conn.cursor()print("Connected to MySQL database successfully!")3. Create a Table
You can use the CREATE TABLE SQL statement to create a table.
# SQL query to create a tablecreate_table_query = """CREATE TABLE employees ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, age INT, department VARCHAR(50), salary DECIMAL(10, 2))"""# Execute the querycursor.execute(create_table_query)print("Table 'employees' created successfully!")4. Verify Table Creation
To check if the table was created, list all tables in the database.
# Show all tables in the databasecursor.execute("SHOW TABLES")# Print all tablesfor table in cursor: print(table)5. Closing the Connection
Always close the database connection after performing operations.
cursor.close()conn.close()print("MySQL connection closed.")Final Complete Code
import mysql.connector# Connect to MySQL Databaseconn = mysql.connector.connect( host="localhost", user="root", password="password", database="mydatabase")cursor = conn.cursor()# Create Table Querycreate_table_query = """CREATE TABLE employees ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, age INT, department VARCHAR(50), salary DECIMAL(10, 2))"""cursor.execute(create_table_query)# Verify Table Creationcursor.execute("SHOW TABLES")for table in cursor: print(table)# Close Connectioncursor.close()conn.close()Summary
| Step | Action |
|---|---|
| 1 | Install mysql-connector-python |
| 2 | Connect to MySQL database |
| 3 | Create a table using CREATE TABLE |
| 4 | Verify table creation using SHOW TABLES |
| 5 | Close the connection |
This is how you can create a MySQL table using Python! ?