python

Creating Database


Creating a database in MySQL using Python can be done using the mysql-connector-python library. Below is a step-by-step guide on how to create a new database.

 

Step 1: Install MySQL Connector

If you haven't installed the MySQL connector, you can do so using pip:

pip install mysql-connector-python
 

 

Step 2: Connect to MySQL Server

To create a database, you'll first need to connect to the MySQL server. This connection does not require specifying a database initially.

import mysql.connector
# Establish a connection to the MySQL server
connection = mysql.connector.connect(
   host="localhost",
   user="your_username",
   password="your_password"
)
# Check if the connection was successful
if connection.is_connected():
   print("Successfully connected to the MySQL server")
 

 

Step 3: Create a Cursor and Execute the Database Creation Query

With the connection established, you can create a cursor object and execute the SQL command to create a database.# Create a cursor object


cursor = connection.cursor()
# Define the SQL query to create a new database
database_name = "new_database"
create_db_query = f"CREATE DATABASE {database_name}"
# Execute the query to create the database
cursor.execute(create_db_query)
print(f"Database '{database_name}' created successfully.")
 

 

Step 4: Handling Errors

It's a good practice to handle errors, especially when dealing with databases. This will ensure your program can handle cases like a database already existing or connection issues.

try:
   # Attempt to create the database
   cursor.execute(create_db_query)
   print(f"Database '{database_name}' created successfully.")
except mysql.connector.Error as err:
   print(f"Failed to create database: {err}")
 

 

Full Example Code

Here's the full code that you can run to create a database in MySQL:

import mysql.connector
try:
   # Establish a connection to the MySQL server
   connection = mysql.connector.connect(
       host="localhost",
       user="your_username",
       password="your_password"
   )
   if connection.is_connected():
       print("Successfully connected to the MySQL server")
       # Create a cursor object
       cursor = connection.cursor()
       # Define the SQL query to create a new database
       database_name = "new_database"
       create_db_query = f"CREATE DATABASE {database_name}"
       # Execute the query to create the database
       cursor.execute(create_db_query)
       print(f"Database '{database_name}' created successfully.")
except mysql.connector.Error as err:
   print(f"Failed to create database: {err}")
finally:
   if connection.is_connected():
       cursor.close()
       connection.close()
       print("MySQL connection is closed")
 

 


python