Reputation: 2455
Using pyodbc I'm working on dealing with executing stored procedures with outputs.
import pyodbc
conn = pyodbc.connect('DRIVER=' + driver + ';PORT=1433;SERVER=' + server +
';PORT=1443;DATABASE=' + database + ';UID=' + username + ';PWD=' + password)
cmd = conn.cursor()
sql = """\
Too long to post
"""
params = ('EOXH39020220', 'EOXH39020245', 'EOXH3E360011')
for item in params:
cmd.execute(sql, item)
rst = cmd.fetchall()
print(rst)
conn.close
The output of a particular stored procedure I am testing with produces the following:
[(False, 1, 3, 2, 967, 6, 'ABC-DE-FGHI', 'LOREM', 'IPSUM', 'CLASS PRODUCT', 'F/P', 'LABELDESCRIPTION', 'N/A', 'DESCRIPTION', 'ASL66', 'ASL10', '3FE50712BA', 'ABC-DE-FGHI', 'PO', 'ITEM#', 'OEM#', 'F/P', '1')]
[(False, 1, 4, 1, 967, 7, 'ABC-DE-FGHI', 'LOREM', 'IPSUM', 'CLASS PRODUCT', 'F/P', 'LABELDESCRIPTION', 'N/A', 'DESCRIPTION', 'ASL66', 'ASL10', '3FE50712BA', 'ABC-DE-FGHI', 'PO', 'ITEM#', 'OEM#', 'F/P', '1')]
[(False, 1, 4, 2, 967, 8, 'ABC-DE-FGHI', 'LOREM', 'IPSUM', 'CLASS PRODUCT', 'F/P', 'LABELDESCRIPTION', 'N/A', 'DESCRIPTION', 'ASL66', 'ASL10', '3FE50712BA', 'ABC-DE-FGHI', 'PO', 'ITEM#', 'OEM#', 'F/P', '1')]
I can't use .split
on it since it's not really a string. How can I split up the contents of a tuple inside of a list? What I am trying to do is break the results back out into variables to use. I'm not getting the results I expect to see. Ex:
testlist = [(False, 1, 3, 2, 967, 6, 'ABC-DE-FGHI', 'LOREM', 'IPSUM', 'CLASS 1 PRODUCT', 'F/P', 'DESCRIPTION', 'N/A', 'DESCRIPTION', 'ASL66', 'ASL10', '3FE50712BA', 'ABC-DE-FGHI', 'PO', 'ITEM#', 'OEM#', 'F/P', '1')]
for i in testlist[0]:
print(testlist[0][i])
results:
False 1 2 3
As suggested by roganjosh, I completely missed what I needed in my loop. first 5 items ex:
testlist = [(False, 1, 3, 2, 967, 6, 'ABC-DE-FGHI', 'LOREM', 'IPSUM', 'CLASS PRODUCT', 'F/P', 'LABELDESCRIPTION', 'N/A', 'DESCRIPTION', 'ASL66', 'ASL10', '3FE50712BA', 'ABC-DE-FGHI', 'PO', 'ITEM#', 'OEM#', 'F/P', '1')]
newlist = []
for x in testlist[0]:
newlist.append(x)
print(newlist[:5])
[False, 1, 3, 2, 967]
Upvotes: 0
Views: 641
Reputation: 13175
The question is a bit confused but we established the issue in comments. Your title is mostly accurate in what's being returned from fetchall()
: a list containing a single tuple, not a dictionary as you go on to state.
fetchall()
is generally used when you expect multiple matches, where each row would be a tuple in the list (so you might consider using fetchone()
as stated by @Barmar in the comments if you're always getting one result).
In the comments, you state that you tried the following but it didn't work:
for i in testlist[0]:
print(testlist[0][i])
It won't - testlist[0]
gives you access to the tuple, but then you try to access that as though it were a dictionary with i
as the key. Instead, i
is the name that is being assigned to each item in that tuple.
The solution is as simple as doing:
for i in testlist[0]:
print(i)
Upvotes: 1