Python MySQL数据库连接实现增删改查

发布时间:2023年12月20日

一、应用场景

python项目连接MySQL数据库时,需要第三方库的支持。这篇文章使用的是PyMySQL库,适用于python3.x。

二、安装

pip install PyMySQL

三、使用方法

1.导入模块

import pymysql

2.连接数据库

db = pymysql.connect(host='localhost',
                     user='code_space',
                     password='code_space_pw',
                     database='demo_db')

3.创建游标对象

cursor = db.cursor()
# 或者
cursor = db.cursor(pymysql.cursors.DictCursor)

# cursor()不加参数的话,查询结果返回的是元组,pymysql.cursors.DictCursor返回的是字典

4)执行sql语句

# 查询
select_sql = " select id,name from user_info "
cursor.execute(select_sql)

# 使用 fetchone() 方法获取单条数据
data = cursor.fetchone()

# 使用 fetchall() 方法获取所有数据
data_list = cursor.fetchall()
# 增删改,这里只演示更新,其它类似
update_sql = " update user_info set name='头条号_code_space' where id = 1 "
cursor.execute(update_sql)
# 提交,执行更新
db.commit()

5)关闭数据库连接

cursor.close()
db.close()

四、测试demo

import pymysql

if __name__ == '__main__':
    db = pymysql.connect(host='localhost',
                         user='root',
                         password='root',
                         database='others')
    # cursor()不加参数的话,查询结果返回的是元组,pymysql.cursors.DictCursor返回的是字典
    cursor = db.cursor(pymysql.cursors.DictCursor)
    # 查询
    select_sql = " select id,name from user_info "
    cursor.execute(select_sql)

    # 使用 fetchone() 方法获取单条数据
    data = cursor.fetchone()
    print("fetchone()使用效果-->")
    print(data)

    # 使用 fetchall() 方法获取所有数据
    cursor.execute(select_sql)
    data_list = cursor.fetchall()
    print("fetchall()使用效果-->")
    print(data_list)

    # 增删改,这里只演示更新,其它类似
    update_sql = " update user_info set name='头条号_code_space' where id = 1 "
    cursor.execute(update_sql)
    # 提交,执行更新
    db.commit()

    cursor.close()
    db.close()

在这里插入图片描述

文章来源:https://blog.csdn.net/qq_23730073/article/details/135114616
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。