问题
i have a pyodbc row with value (9, ) I am trying to read the value into a simple integer variable, and i find that its so hard to do so. (i am new to python so i probably miss something dumb)
doing a simple int(a_row[0])
get -
TypeError: int() argument must be a string or a number, not 'pyodbc.Row'
i try to cast the row into a list first, and its the same result
i had to force it into a integer value to work
row_id=(2, )
temp_num=0
temp_num = [number for number in row_id[0]]
temp_num=int(temp_num[0])
i just find it really bizarre that i have to do something so silly, so it must be my fault, can anyone enlighten me, where i got it wrong?
回答1:
Your solution isn't forcing it into an integer; it is creating an array of the elements (the Row
s) in row_id[0]
, and then extracting the first one. So you could have just done a_row[0][0]
initially.
回答2:
The output of fetchall of a query is a list of pyodbc.Rows:
>>> x=cursor.execute('SELECT x FROM my_tbl limit 5;').fetchall()
>>> print(x) # list of elements of type pyodbc.Row
[(3, ), (2, ), (0, ), (5, ), (1, )]
>>> type(x[0])
pyodbc.Row
to get actual integers pulled by the query above do this
>>> [row[0] for row in x]
[3, 2, 0, 5, 1]
来源:https://stackoverflow.com/questions/25652851/how-to-convert-a-list-value-into-int