当前位置:首页 » python运维 » 正文

pymysql之cur.fetchall() 和cur.fetchone()用法详解

看: 1230次  时间:2020-07-08  分类 : python运维

我就废话不多说了,大家还是直接看代码吧!

import pymysql,hashlib
结果:单条结果 {'id': 1, 'name': '打车', 'phone': '132453'}

sql = 'select * from zxj'
def op_mysql(sql,many=True):
 db_info = {'user': 'jxz', 'password': '123456',
  'host': '118*******', 'db': 'jxz', 'port': 3306, 'charset': 'utf8',
  'autocommit': True}
 conn = pymysql.connect(**db_info) # 建立连接
 cur = conn.cursor(pymysql.cursors.DictCursor) # 游标
 cur.execute(sql) # 执行sql语句,insert 、update 、delete
 if many:
 result = cur.fetchall()
 print('多条',result)
 else:
 result = cur.fetchone() # {''}
 print('dantiao',result)
 cur.close()
 conn.close()
 return result
op_mysql(sql,many=False) # 传入sql, 默认为true

=================================
md5加盐2
def md5(s,salt=''):
 new_s = str(s) + salt
 m = hashlib.md5(new_s.encode())
 return m.hexdigest()```

补充知识:python pymssql使用时,使用fetchone获取的值怎么在while里操作多条数据

项目描述:

想把status状态为1的数据查出来然后再通过while 遍历update 数据,为了清楚测试时候的数据。

刚开始的代码是这样的。

#coding:utf-8
import pymssql
def connect():
connect=pymssql.connect((‘x.x.x.x'),‘x',‘x',‘x')

cursor = connect.cursor() # 创建游标
sql001='select *from xxxxx where xxxxx=273and Status=1 order by sysno desc'#查询语句
cursor.execute(sql001)
row=cursor.fetchone()#读取查询结果
print(row)
if row==None:
 print("没有查到数据")
else:

 while row:
 print("sysno=%s" % (row[0]))
 cursor.execute("update xxxxx set Status=-1 where SysNo=%d", row[0]) # 执行语句\
 connect.commit()
 print(row)
 #cursor.execute(sql001)
 row=cursor.fetchone()
 #print(row)

connect()

报错信息:

File “D:/JiCaiZhuanTi/Case/test.py”, line 22, in connect
row=cursor.fetchone()
File “src\pymssql.pyx”, line 507, in pymssql.Cursor.fetchone
pymssql.OperationalError: Statement not executed or executed statement has no resultset

自己查了不少文章,以前没有对这块有所涉及,因为本人是菜鸟,用到哪就看到哪。也仔细看了fetchone() 、fetchall() 还有pymssql的对数据库的基本炒作。看了好久在最后灵光一闪理解错误在哪里了。

错误出在while里的connect.commit()后直接又row=cursor.fetchone()而while里是(返回单个的元组,也就是一条记录(row),如果没有结果 则返回 None)因为我上一个查询是update语句,更新sql语句不会返回resultset,所以会报错。

然后我就这样改了一下,:

while row:
print(“sysno=%s” % (row[0]))
cursor.execute(“update xxxxx set Status=-1 where SysNo=%d”, row[0]) # 执行语句
connect.commit()
print(row)
cursor.execute(sql001)
row=cursor.fetchone()

在获取sql执行获取结果的 row=cursor.fetchone()我再去调用一次查询再次获取想要的数据。

我觉得应该有更好的办法,就是再第一次获取查询结果把所需要的sysno都拿出来,然后再while,这样可以减少对数据库的调用。

目前还没有写出来代码,不知道思路对不对,大家可以留言讨论下。

以上这篇pymysql之cur.fetchall() 和cur.fetchone()用法详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持python博客。

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!