Python 数据库应用教程:安装 MySQL 及使用 MySQL Connector


Python 数据库应用教程:安装 MySQL 及使用 MySQL Connector

在本教程中,我们将介绍如何在系统上安装 MySQL,并使用 Python 的 MySQL Connector 与 MySQL 数据库进行交互。我们将涵盖以下内容:

  1. 安装 MySQL
  2. 安装 MySQL Connector
  3. 使用 MySQL Connector 连接数据库
  4. 创建数据库和表格
  5. 插入数据
  6. 查询数据

1. 安装 MySQL

Windows

  1. 下载并运行 MySQL Installer: MySQL Installer

  2. 安装 MySQL Server 和 MySQL Workbench,按照安装向导的步骤进行操作。

  3. 安装完成后,使用 MySQL Workbench 或命令行配置 MySQL 实例并创建用户。

macOS

使用 Homebrew 安装 MySQL:

brew install mysql
brew services start mysql

Linux

在 Ubuntu 上安装 MySQL:

sudo apt update
sudo apt install mysql-server
sudo systemctl start mysql
sudo systemctl enable mysql

2. 安装 MySQL Connector

安装 mysql-connector-python 库:

pip install mysql-connector-python

3. 使用 MySQL Connector 连接数据库

创建一个连接到 MySQL 数据库的 Python 脚本:

import mysql.connector

def connect_to_db():
    conn = mysql.connector.connect(
        host='localhost',
        user='yourusername',
        password='yourpassword',
        database='yourdatabase'
    )
    return conn

# 测试连接
conn = connect_to_db()
if conn.is_connected():
    print("Connected to MySQL database")
conn.close()

4. 创建数据库和表格

创建一个名为 testdb 的数据库和一个名为 employees 的表格:

def create_database(cursor):
    cursor.execute("CREATE DATABASE IF NOT EXISTS testdb")
    cursor.execute("USE testdb")

def create_table(cursor):
    create_table_query = '''
    CREATE TABLE IF NOT EXISTS employees (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(255) NOT NULL,
        age INT NOT NULL,
        position VARCHAR(255) NOT NULL
    )
    '''
    cursor.execute(create_table_query)

# 连接到 MySQL 并创建数据库和表格
conn = connect_to_db()
cursor = conn.cursor()
create_database(cursor)
create_table(cursor)
conn.commit()
cursor.close()
conn.close()

5. 插入数据

编写一个函数来插入数据:

def insert_employee(cursor, name, age, position):
    insert_query = '''
    INSERT INTO employees (name, age, position)
    VALUES (%s, %s, %s)
    '''
    cursor.execute(insert_query, (name, age, position))
    return cursor.lastrowid

# 连接到数据库并插入数据
conn = connect_to_db()
cursor = conn.cursor()
cursor.execute("USE testdb")
employee_id = insert_employee(cursor, 'John Doe', 30, 'Software Engineer')
print(f'Inserted employee with ID: {employee_id}')
conn.commit()
cursor.close()
conn.close()

6. 查询数据

编写一个函数来查询数据:

def fetch_employees(cursor):
    query = "SELECT * FROM employees"
    cursor.execute(query)
    return cursor.fetchall()

# 连接到数据库并查询数据
conn = connect_to_db()
cursor = conn.cursor(dictionary=True)
cursor.execute("USE testdb")
employees = fetch_employees(cursor)
for employee in employees:
    print(employee)
cursor.close()
conn.close()

综合示例

将所有步骤组合在一个完整的脚本中:

import mysql.connector

def connect_to_db():
    conn = mysql.connector.connect(
        host='localhost',
        user='yourusername',
        password='yourpassword',
        database='testdb'
    )
    return conn

def create_database(cursor):
    cursor.execute("CREATE DATABASE IF NOT EXISTS testdb")
    cursor.execute("USE testdb")

def create_table(cursor):
    create_table_query = '''
    CREATE TABLE IF NOT EXISTS employees (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(255) NOT NULL,
        age INT NOT NULL,
        position VARCHAR(255) NOT NULL
    )
    '''
    cursor.execute(create_table_query)

def insert_employee(cursor, name, age, position):
    insert_query = '''
    INSERT INTO employees (name, age, position)
    VALUES (%s, %s, %s)
    '''
    cursor.execute(insert_query, (name, age, position))
    return cursor.lastrowid

def fetch_employees(cursor):
    query = "SELECT * FROM employees"
    cursor.execute(query)
    return cursor.fetchall()

def main():
    conn = connect_to_db()
    cursor = conn.cursor(dictionary=True)

    create_database(cursor)
    create_table(cursor)

    employee_id = insert_employee(cursor, 'John Doe', 30, 'Software Engineer')
    print(f'Inserted employee with ID: {employee_id}')

    conn.commit()

    employees = fetch_employees(cursor)
    for employee in employees:
        print(employee)

    cursor.close()
    conn.close()

if __name__ == "__main__":
    main()

通过这些步骤,你可以在 Python 中使用 MySQL Connector 进行数据库创建、数据插入及数据查询操作。


原文链接:codingdict.net