import pymysql # 打开数据库连接 connection = pymysql.connect(host='127.0.0.1', user='root', passwd='146', db='student', # 数据库名 port=3306, charset='utf8' ) try: # 使用cursor()方法获取操作游标 # cur = connection.cursor() # 获取到的结果是元组 cur = connection.cursor(pymysql.cursors.DictCursor) # 获取到的结果是字典 # SQL 插入语句 sql = "select id,course from course" # 执行sql语句 connection.commit() # 当有数据被修改时提交到数据库执行 ret = cur.execute(sql) print(ret) con = cur.fetchone() print(con) con = cur.fetchmany(3) # con = cur.fetchall() print(con) cur.close() except Exception: connection.rollback() # 如果发生错误则回滚 finally: # 关闭数据库连接 connection.close()