pymysql增删改查

import pymysql

connection = pymysql.connect(#链接数据库
    host='localhost',
    user='root',
    password='********',
    db='studentsdb',
)


def find_data():
    cursor = connection.cursor()  # 创建游标.
    # SQL语句
    sql = 'select * from tb_user'
    # execute执行操作
    cursor.execute(sql)
    result = cursor.fetchall()
    print(type(result), cursor.rowcount)
    print(result)
    for i in result:
        print(i)
    cursor.close()

def add_data():
    cursor = connection.cursor()  # 创建游标.
    # 插入SQL语句
    sql = 'insert into tb_user(url,username,password) values (%s,%s,%s)'
    # 插入数据
    data = [
        ('123', '刘博蛋', '54238'),
        ('321', '王成杰', '54238'),
    ]
    #print(type(data[0]))
    # 拼接并执行SQL语句
    cursor.executemany(sql, data)
    # 涉及写操作要提交
    connection.commit()
    #print(cursor.rowcount)
    cursor.close()

def delete():
    cursor = connection.cursor()  # 创建游标.
    # 删除SQL语句
    sql = 'delete from tb_user where url = "123"'
    cursor.execute(sql)
    connection.commit()
    print(cursor.rowcount)
    cursor.close()


def update():
    cursor = connection.cursor()  # 创建游标.
    # 修改SQL语句
    sql = 'update tb_user set url="12345622" where password="123"'
    # 执行SQL语句
    cursor.execute(sql)
    connection.commit()
   # print(cursor.rowcount)
    cursor.close()

add_data()
delete()
find_data()
update()


connection.close()

posted @   冷月半明  阅读(11)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示