MySQL is a popular open-source database management system which is being used by many organizations for data storage and retrieval. Python is a widely used high-level programming language which can be used for scripting, automation, web development, and many other domains including database programming. In this tutorial, we will learn how to create a database using Python and MySQL database management system.
Prerequisites
To follow along with this tutorial, you will need:
- Python 3 installed on your system
- pip installed
- mysql-connector-python module installed
Installing mysql-connector-python
You can install mysql-connector-python module using pip which is a package installer for Python. To install the module, run the following command:
pip install mysql-connector-python
Creating a Database using Python
First, import the mysql-connector module in your Python code. This module provides various classes and methods which can be used to interact with MySQL database.
import mysql.connector
Next, establish a connection to your MySQL database. You need to provide connection details such as hostname, username, password, and database name.
mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword" )
Once you have connected to the database, you can create a new database using the following code:
mycursor = mydb.cursor() mycursor.execute("CREATE DATABASE mydatabase")
The above code will create a new database named mydatabase in your MySQL database management system.
Example 1: Create a Database using Python
Here is a complete example which demonstrates how to create a new database using Python:
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword" ) mycursor = mydb.cursor() mycursor.execute("CREATE DATABASE mydatabase") print("Database Created Successfully!")
When you run the above code, you will see the following output:
Database Created Successfully!
Example 2: Create a Database with Specific Charset and Collation using Python
You can create a database with a specific charset and collation using the following code:
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword" ) mycursor = mydb.cursor() mycursor.execute("CREATE DATABASE mydatabase CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci") print("Database Created Successfully!")
The above code will create a new database named mydatabase with charset utf8mb4 and collation utf8mb4_unicode_ci in your MySQL database management system. You can modify the charset and collation values as per your requirements.
Conclusion
In this tutorial, we learned how to create a database using Python and MySQL database management system. We also learned how to install the mysql-connector-python module and use it to establish a connection with the database, and how to create a new database using Python.