欢迎访问宙启技术站
智能推送

如何使用Python在MySQL数据库中进行数据操作

发布时间:2023-12-26 10:08:28

在Python中,可以使用第三方库mysql-connector-python来连接 MySQL 数据库并进行数据操作。下面是一个示例:

1. 安装 mysql-connector-python:

可以使用 pip 命令来安装该库:

pip install mysql-connector-python

2. 导入必要的库:

import mysql.connector
from mysql.connector import Error

3. 建立数据库连接:

try:
    connection = mysql.connector.connect(
        host='localhost',
        database='mydb',
        user='root',
        password='password'
    )
    if connection.is_connected():
        print('连接到MySQL数据库...')
except Error as e:
    print(f'无法连接到数据库:{e}')

4. 创建数据表:

def create_table(connection):
    create_table_query = '''
        CREATE TABLE IF NOT EXISTS employees (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(255) NOT NULL,
            age INT,
            department VARCHAR(255)
        )
    '''
    try:
        cursor = connection.cursor()
        cursor.execute(create_table_query)
        connection.commit()
        print('数据表已创建成功!')
    except Error as e:
        print(f'无法创建数据表:{e}')

5. 插入数据:

def insert_data(connection, name, age, department):
    insert_query = '''
        INSERT INTO employees (name, age, department)
        VALUES (%s, %s, %s)
    '''
    record = (name, age, department)
    try:
        cursor = connection.cursor()
        cursor.execute(insert_query, record)
        connection.commit()
        print('数据已成功插入!')
    except Error as e:
        print(f'无法插入数据:{e}')

6. 查询数据:

def select_data(connection):
    select_query = '''
        SELECT * FROM employees
    '''
    try:
        cursor = connection.cursor()
        cursor.execute(select_query)
        records = cursor.fetchall()
        print('查询结果:')
        for record in records:
            print(record)
    except Error as e:
        print(f'无法查询数据:{e}')

7. 更新数据:

def update_data(connection, employee_id, new_department):
    update_query = '''
        UPDATE employees
        SET department = %s
        WHERE id = %s
    '''
    data = (new_department, employee_id)
    try:
        cursor = connection.cursor()
        cursor.execute(update_query, data)
        connection.commit()
        print('数据已成功更新!')
    except Error as e:
        print(f'无法更新数据:{e}')

8. 删除数据:

def delete_data(connection, employee_id):
    delete_query = '''
        DELETE FROM employees
        WHERE id = %s
    '''
    data = (employee_id,)
    try:
        cursor = connection.cursor()
        cursor.execute(delete_query, data)
        connection.commit()
        print('数据已成功删除!')
    except Error as e:
        print(f'无法删除数据:{e}')

9. 关闭数据库连接:

def close_connection(connection):
    try:
        if connection.is_connected():
            connection.close()
            print('连接已关闭!')
    except Error as e:
        print(f'无法关闭连接:{e}')

最后,可以通过以下方式来使用上述的函数:

# 创建数据表
create_table(connection)

# 插入数据
insert_data(connection, 'John', 30, 'HR')

# 查询数据
select_data(connection)

# 更新数据
update_data(connection, 1, 'Sales')

# 删除数据
delete_data(connection, 1)

# 关闭数据库连接
close_connection(connection)

以上就是在Python中使用mysql-connector-python库进行MySQL数据库操作的示例。当然,还有其他更多的操作方法,可以根据自己的需求进行相应的修改和扩展。