python连接数据库的操作

import pymysql

con = pymysql.connect(host="xxxx", port=xxx, user="root", password="123456",charset="utf8",cursorclass=pymysql.cursors.DictCursor, database="test20")
cur = con.cursor()

con.commit()
cur.execute("SELECT * FROM `class`;")

res1 = cur.fetchall()
# 得到:[{'Id': '1', 'Name': '一班'}, {'Id': '2', 'Name': '二班'}]
# 连接数据库时没把cursorclass定义成字典形式的话:(('1', '一班'), ('2', '二班'))

res2 = cur.fetchone()
# 不执行上面fetchall的情况下得到:{'Id': '1', 'Name': '一班'}    如果执行了上面的fetchall,这里就是None了

res3 = cur.fetchone()
# 在运行过一次fetchone后再运行一次:{'Id': '2', 'Name': '二班'}

print(res1)
# print(res2)
# print(res3)

cur.close()
con.close()

 

posted @ 2022-01-14 21:28  2orange  阅读(148)  评论(0编辑  收藏  举报