python操作mysql数据库实现增删改查(curd)

本文详细介绍如何使用Python的pymysql模块连接并操作MySQL数据库,包括安装模块、创建连接、执行SQL语句、增删改查操作及结果集的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、在终端安装数据库模块:

sudo pip3 install pymysql

二、在.py文件中导入pymysql模块

from pymysql import *

三、创建连接对象

conn = connect(host="localhost", port=3306, user="用户名", password="密码", database="数据库名", charset="utf8")

四、创建游标对象

cursor = conn.cursor()

五、execute执行sql语句

sql = "增、删、改、查 语句"
cursor.execute(sql)
cursor.execute("select * from goods")
# 生效的行数,游标中存储的是信息。
# 取查询的结果
cursor.fetchone()	# 执行一次fetchone()显示游标中的一条记录
cursor.fetchmany()
cursor.fetchall()	# 显示游标中除当前显示过的剩余的全部记录
"""
备注:
1、增删改查语句都要放在execute(" ")中执行。
2、执行完增、删、改命令后一定要提交(conn.commit())
3、在
"""

六、关闭

关闭游标

cursor.close()

–关闭连接对象

conn.close()

注意:一定要先关闭游标,在关闭连接对象

案例:增、删、改、查

from pymysql import *

def main():
    # 1、创建Connection连接
    conn = connect(host='localhost',port=3306,user='root',password='root',database='jing_dong',charset='utf8')
    # 2、获得Cursor对象
    cursor = conn.cursor()
    # 3、查询
    find_name = input("请输入物品名称:")
    # 非安全的方式  (sql注入问题)
    # 输入 " or 1=1 or "   (双引号也要输入)
    # sql = """select * from goods where name="%s" """ % find_name
    # print("""sql===>%s<====""" % sql)
    # 执行select语句,并返回受影响的行数:查询所有数据
    # count = cursor.execute(sql)

    # 安全的方式  (简单避免sql注入问题)
    # 构造参数列表
    params = [find_name]
    # 执行select语句,并返回受影响的行数:查询所有数据
    count = cs1.execute('select * from goods where name=%s', params)
    """
    注意:
    如果要是有多个参数,需要进行参数化
    那么params = [值1, 值2....],此时sql语句中有多个%s即可 
    """
   
    #  打印受影响的行数
    print("查询到%d条数据:" % count)
	# 遍历显示查询到的记录
    for i in range(count):
        # 获取查询的结果
        result = cursor.fetchone()
        # 打印查询的结果
        print(result)
   # 4、增、删、改
    # (1)增加
    count = cs1.execute('insert into goods_cates(name) values("硬盘")')
    # 打印受影响的行数
    print(count)

    count = cs1.execute('insert into goods_cates(name) values("光盘")')
    print(count)

    # (2)更新
    # count = cs1.execute('update goods_cates set name="机械硬盘" where name="硬盘"')
    # (3)删除
    # count = cs1.execute('delete from goods_cates where id=6')

    # (4)提交之前的操作,可以执行多次增、删、改语句,最后提交
   	 conn.commit()

    # 关闭Cursor对象
    cs1.close()
    conn.close()

if __name__ == '__main__':
    main()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值