python操作MySQL----增删改查

1.  导入包

import pymysql

2.  创建连接

con = pymysql.connetc(host='localhost', user='root', password='123456', database='mysql_db', port=3306)

3.  获取游标

cur = con.cursor()

4.1 插入一条数据

insert_sql = 'insert into student(sname, sex, age, score) values(%s, %s, %s, %s)'

try:

    cur.execute(insert_sql, ('name', '男', 20, 99.5)

    #提交事务

    con.commit()

except Exception as e:

    print(e)

    con.rollback()#插入失败,回滚

finally:

    cur.close()

    con.close()

4.2  插入多条数据

try:

    cur.executemany(insert_sql, [('小明', '男', 28, 99), ('小花', '女', 25, 95.5), ('小红', '女', 18, 90)])

    con.commit()#提交事务

except Exception as e:

    print(e)

    con.rollback()#插入失败,回滚

finally:

    cur.close()

    con.close()

4.3  删除数据

del_sql = 'delete from t_person where sname=%s'

try:

    cur.execute(delete_sql, ('name'))#sqlite3里面一个参数的时候需要添加一个逗号

    con.commit()#提交事务

except Exception as e:

    print(e)

    con.rollback()#删除失败则回滚

finally:

    cur.close()

    con.close()

4.4  查询一条数据

query_sql = '''

    select * from student where age<=28

'''

try:

    cur.execute(query_sql)

    #获取一条数据

    person = cur.fetchone()

    print(person)

except Exception as e:

    print(e)

finally:

    cur.close()

    con.close()

4.5  查询所有数据

try:

    cur.execute(query_sql)

    persons = cur.fetchall()

    for person in persons:

        print(person)

except Exception as e:

    print(e)

finally:

    cur.close()

    con.close()
————————————————
版权声明:本文为优快云博主「luco2008」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.youkuaiyun.com/luco2008/article/details/102620418

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值