Python的try except在添加for循环后不起作用。

huangapple go评论49阅读模式
英文:

Python try except not working when adding for loop after

问题

抱歉,我只会翻译文本内容,以下是代码的翻译:

powder = []
try:
    cnxn = p.connect('DRIVER={/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.5.so.2.1};SERVER='+server+';DATABASE='+db+';UID='+un+';PWD='+pw)
    cursor = cnxn.cursor()
    cursor.execute("SELECT * FROM Table WHERE Something='THING'")
    powd = cursor.fetchall()
except:
    powd = [['DUCKS']]

for p in powd:
     powder.append(p[0])

希望这对你有所帮助。

英文:

Not sure what the issue is with this, as I am using the same code in several places but is only breaking in one place. Connecting to sql db to append values to a list. Python 3.x

powder = []
try:
    cnxn = p.connect('DRIVER={/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.5.so.2.1};SERVER='+server+';DATABASE='+db+';UID='+un+';PWD='+pw)
    cursor = cnxn.cursor()
    cursor.execute("SELECT * FROM Table WHERE Something='THING'")
    powd = cursor.fetchall()
except:
    powd = [['DUCKS']]

for p in powd:
     powder.append(p[0])

If the for loop is left off, it runs perfectly, the try succeeds and powd has all my needed values. When I add the for loop the try fails every time (first line doesn't even run).
I tried moving the for loop into the try and also tried adding a finally after except.
I am running this same code for different SQL Statements (most of which are more complex/larger datasets) and this code works perfect. Not sure what could be causing it to fail in this or how to get around it. Any thoughts/suggestions are appreciated.

答案1

得分: 1

我已经弄清楚了

import pyodbc as p

for循环正在使用p作为变量,一旦我将其更改为pn,它就像魔术一样工作。试图使用我已经设置的变量。糟糕。

for pn in powd:
     powder.append(pn[0])
英文:

Figured it out

import pyodbc as p

for loop was using p as the variable, once I changed that to pn it worked like a charm. Was trying to use a variable I already had set. Opps.

for pn in powd:
     powder.append(pn[0])

huangapple
  • 本文由 发表于 2023年4月20日 00:25:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76056839.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定