MySQL Create Database
Python is a popular programming language that is widely used for web development, data analysis, and artificial intelligence. One of the most common use cases
Python is a popular programming language that is widely used for web development, data analysis, and artificial intelligence. One of the most common use cases for Python is to interact with databases. MySQL is one of the most popular relational database management systems (RDBMS) used in web development. In this tutorial, we will show how to create a MySQL database using Python.
Prerequisites
To create a MySQL database in Python, ensure you have Python and the MySQL connector installed. Download Python from the official website. Then, install the connector using pip, Python's package installer:
pip install mysql-connector-pythonConnecting to MySQL
Before creating a database, you must connect to a MySQL server. Provide the host, user, and password for your server. Here is an example of how to establish a connection:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
print(mydb)
mydb.close()Creating a Database
Once connected, you can create a new database using the CREATE DATABASE statement:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE IF NOT EXISTS mydatabase")
mycursor.close()
mydb.close()Using IF NOT EXISTS prevents a runtime error if the database already exists.
Listing Existing Databases
To verify which databases are available, you can use the SHOW DATABASES statement. This lists all databases on the server:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print(x)
mycursor.close()
mydb.close()Using the Database
After creating the database, switch to it using the USE statement:
mycursor.execute("USE mydatabase")Conclusion
This tutorial covered the prerequisites, connecting to MySQL, creating a database, and listing existing databases. By following these steps, you can set up a MySQL database in Python for your web applications. If you have any questions or comments, please feel free to leave them below.