import pymysql
# 连接数据库
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='12345678', db='test')
# 游标默认返回元组
# cursor = conn.cursor()
# 游标设置为字典,fetch返回字典格式
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 执行sql
cursor.execute("insert into account (username,password) values ('a','a')")
# 让改动更新到数据库
conn.commit()
# 获取数据
cursor.execute("select * from account")
data = cursor.fetchall()
print('移动前',data)
# 移动游标
cursor.scroll(0,'absolute') # 绝对位置
# cursor.scroll(1,'relative') 相对位置
data2 = cursor.fetchall()
print('移动后',data2)
# 获取自增id
cursor.execute("insert into account (username,password) values ('b','b')")
new_id = cursor.lastrowid
print('新id:',new_id)
# 关闭游标和数据库连接
cursor.close()
conn.close()
来源:CSDN
作者:weixin_38892128
链接:https://blog.csdn.net/weixin_38892128/article/details/103585623