英文:
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])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论