使用临时列名而不是索引从 MySQL/Python 查询中检索数据
Retrieve data from MySQL/Python query using temporary column names not index
如何使用列名从 MySQL 查询中检索数据(我只是按索引使用它)。例如,这是我的示例代码:
query = ('SELECT Column1 as name, Column2 as lastname, Column 3 as othername FROM '
'table WHERE condition = 1 ORDER BY name ASC LIMIT 1')
cursor.execute(query) # I'll get just 1 result
results = cursor.fetchall()
if not results:
connection.close()
..
else:
for row in results:
var = row[0] # <- Here is the problem, I am using the index to retrieve
# the result from query, I wanna to use 'var = row["name"]' instead
# but this throw me an error because row must be integer type
...
我希望你能帮助我。谢谢,祝你有个愉快的一天。
嘿,为了使用 'row["name"]',您需要制作一个查询字典。这可以通过使用 dictcursor 来完成...
光标 = connection.cursor(pymysql.cursors.DictCursor)
cursor.execute(查询)
希望这对您有所帮助:)
如何使用列名从 MySQL 查询中检索数据(我只是按索引使用它)。例如,这是我的示例代码:
query = ('SELECT Column1 as name, Column2 as lastname, Column 3 as othername FROM '
'table WHERE condition = 1 ORDER BY name ASC LIMIT 1')
cursor.execute(query) # I'll get just 1 result
results = cursor.fetchall()
if not results:
connection.close()
..
else:
for row in results:
var = row[0] # <- Here is the problem, I am using the index to retrieve
# the result from query, I wanna to use 'var = row["name"]' instead
# but this throw me an error because row must be integer type
...
我希望你能帮助我。谢谢,祝你有个愉快的一天。
嘿,为了使用 'row["name"]',您需要制作一个查询字典。这可以通过使用 dictcursor 来完成...
光标 = connection.cursor(pymysql.cursors.DictCursor) cursor.execute(查询)
希望这对您有所帮助:)