How to Create and Use a MySQL Database in Python
In this tutorial, we will learn how to create a MySQL database and how to manipulate it using Python.
Step 1: Install MySQL Connector
To interact with a MySQL database using Python, you need to install the mysql-connector-python
package.
pip install mysql-connector-python
Step 2: Create a Database
The following Python code creates a database named mydatabase
:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="your_password"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatabase")
Step 3: Create a Table
You can create a table in the database using the CREATE TABLE
SQL command. Here’s how:
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="your_password",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), email VARCHAR(255))")
Step 4: Insert Data
To insert data into the table, you can use the INSERT INTO
SQL command:
sql = "INSERT INTO users (name, email) VALUES (%s, %s)"
val = ("John Doe", "john@example.com")
mycursor.execute(sql, val)
mydb.commit()