Python MySQL Create Database

To create a MySQL database using Python, you can follow these steps:

1. Install MySQL Connector

First, ensure that you have the mysql-connector-python installed:

pip install mysql-connector-python

2. Connect to MySQL Server

You’ll need to connect to the MySQL server (not a specific database) to create a new database.

Example Python Script to Create a Database

import mysql.connector

# Connect to the MySQL server
mydb = mysql.connector.connect(
  host="localhost",        # Change this to your MySQL host if different
  user="yourusername",      # Change this to your MySQL username
  password="yourpassword"   # Change this to your MySQL password
)

# Create a cursor object
mycursor = mydb.cursor()

# Create a new database
mycursor.execute("CREATE DATABASE mynewdatabase")

# Check if the database was created successfully
mycursor.execute("SHOW DATABASES")

for db in mycursor:
    print(db)

Explanation:

  • mysql.connector.connect(): Connects to the MySQL server using the provided host, username, and password.
  • mycursor.execute("CREATE DATABASE mynewdatabase"): Creates a new database called mynewdatabase.
  • mycursor.execute("SHOW DATABASES"): Lists all the available databases on the MySQL server to verify the newly created database.

Output:

If successful, the database mynewdatabase will be created, and when printing the result of SHOW DATABASES, you should see it listed among other databases.

3. Using the Created Database

Once the database is created, you can modify your connection string to use it:

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="mynewdatabase"   # Use the newly created database
)

Now, you’re ready to create tables and insert data into the newly created mynewdatabase.

Leave a Reply 0

Your email address will not be published. Required fields are marked *