import pymysql import pandas from IPython.core.display import display db = pymysql.connect( host=‘localhost‘, port=3306, user=‘root‘, password=‘root‘, db=‘test‘, charset=‘utf8‘ ) cursor = db.cursor() sql = "select * from user" result = cursor.execute(sql) # result 接收的是总条数 是一个 int 值 print(result) data = cursor.fetchone() # print(data) # fet** 系列的方法 是提取结果,不是拷贝 resultSet = cursor.fetchall() print(resultSet) for i in resultSet: print(i) print(len(resultSet)) print(resultSet[0]) resultSet2 = cursor.fetchall() print(resultSet2) for i in range(len(resultSet)): print(i) print(resultSet[i]) cursor.execute(sql) resultSet = cursor.fetchall() for a,b,c in resultSet: print(" 我的名字是{} ,编号是 {} , 这是我的密码{}".format(b,a,c)) # 用表格显示 df1 = pandas.read_sql(sql,db) display(df1) sqlinsert = ‘insert into user (uname,pwd)values ("牛魔王","123123")‘ try: cursor.execute(sqlinsert) db.commit() except: print("insert failed") db.rollback() sqlinsert2 = ‘insert into user (uname,pwd)values (%s,%s)‘ insertdata = [("孙悟空","123456"),("唐僧","123123")] try: cursor.executemany(sqlinsert2,insertdata) db.commit() except: print("insertFailed") db.rollback() sqlupdate = ‘update user set pwd=%s where name=%s‘ try: cursor.execute(sqlupdate,[90000,"玉皇大帝"]) db.commit() except: print("update failed") db.rollback() db.close();
总结:
- 第一: display() 函数来自 ipython ,注意导包
- 第二:result = cursor.execute(sql)
- result 值的为 查询的结果数
- 第三:resultSet = cursor.fetchall()
- 提取结果
- 第四:(%s,%s) 用于匹配给的数据,s 表示字符串
- 第五: for 语句的给了三种用法
- 直接 用 in 关键字,匹配一条结果(或子元素)
- range(int a) 给出迭代范围 0~a
- a,b,c in resultSet a,b,c 按顺序匹配
- 第六:pymysql 默认事务是开启的,手动提交
原文地址:https://www.cnblogs.com/lightandtruth/p/12523601.html
时间: 2024-11-08 21:42:08