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