Mysql Create Database in Python
MySQL Create Database in Python
In Python, you can use the mysql-connector-python library to create a MySQL database.
1. Install MySQL Connector
First, install the MySQL connector if you haven't already:
pip install mysql-connector-python2. Connect to MySQL Server
Before creating a database, you need to connect to the MySQL server.
import mysql.connector# Connect to MySQL Serverconn = mysql.connector.connect( host="localhost", # Change to your MySQL host user="root", # Change to your MySQL username password="password" # Change to your MySQL password)# Create a cursor objectcursor = conn.cursor()print("Connected to MySQL server successfully!")3. Create a Database
# SQL query to create a new databasecursor.execute("CREATE DATABASE mydatabase")print("Database 'mydatabase' created successfully!")4. Verify Database Creation
You can check if the database was created successfully by listing all databases:
# Show all databasescursor.execute("SHOW DATABASES")# Print all databasesfor db in cursor: print(db)5. Connect to the New Database
Once the database is created, you can connect to it:
# Connect to the newly created databaseconn = mysql.connector.connect( host="localhost", user="root", password="password", database="mydatabase")print("Connected to 'mydatabase' successfully!")6. Closing the Connection
After you're done, always close the connection.
cursor.close()conn.close()Final Complete Code
import mysql.connector# Connect to MySQL Serverconn = mysql.connector.connect( host="localhost", user="root", password="password")cursor = conn.cursor()# Create Databasecursor.execute("CREATE DATABASE mydatabase")# Verify Creationcursor.execute("SHOW DATABASES")for db in cursor: print(db)# Close Connectioncursor.close()conn.close()Summary
| Step | Action |
|---|---|
| 1 | Install mysql-connector-python |
| 2 | Connect to MySQL Server |
| 3 | Create a database using CREATE DATABASE dbname |
| 4 | Verify the database using SHOW DATABASES |
| 5 | Connect to the new database |
| 6 | Close the connection |
This is how you can create a MySQL database using Python! ?