接着上一篇的代码做了一下优化。上一篇在获取查询结果时使用了fetchone,现在改成fetchall来减少对数据库的操作:

SQL批量更新技巧
本文介绍了一种使用Python和pymssql模块优化SQL操作的方法。通过将fetchone替换为fetchall,一次性获取所有查询结果,然后在循环中进行批量更新,避免了每次循环重新连接数据库的效率低下问题,显著提高了数据库操作的性能。

#coding:utf-8
import pymssql
def connect():
connect=pymssql.connect((‘xxxx’),‘xx’,‘xxxx’,‘xxxx’)

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 xxxxxset Status=-1 where SysNo=%d", row[0])  # 执行语句\
        connect.commit()
        print(row)
        cursor.execute(sql001)
        row=cursor.fetchone()
        #print(row)

connect()
这个也能实现我的所需要的功能,就是把查询出来的数据的syson作为update语句的条件。这个不好的就是在循环时没循环一次就要调用数据连接执行sql语句,会影响性能和加大资源的开销。
现在改成的代码如下:
#coding:utf-8
import pymssql
def connect():
connect=pymssql.connect((‘xxxxx’),‘sa’,‘xxxxx’,‘xxxxxx’)

cursor = connect.cursor()  # 创建游标
sql001='select *from xxxx where xxxx=273and Status=1 order by sysno desc'#查询语句
cursor.execute(sql001)
#row=cursor.fetchone()#读取查询结果
rowall=cursor.fetchall()#获取所有查询结果
print(rowall)
i=0



#print(row)
if rowall==[]:
    print("没有查到数据")
else:


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

        #print(row)
       ##row=cursor.fetchone()
        #print(row)'''

connect()
之前使用了fetchone 现在使用fetchall一次那多所有查询结果再用while 获取所需要的值,这样就会减少执行完update语句再次执行一次查询语句,减少了对数据库的操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值