我是Python的初学者。我想将SQL查询结果转换为列表。以下是我的代码:
cursor = connnect_db()
query = "SELECT * FROM `tbl`"
cursor.execute(query)
options = list()
for i,row in enumerate(cursor.fetchall()):
options.append(row[i])
我的表格有6列,但这段代码没有创建6个元素列表。我做错了什么?
如果你在Python中有一个可迭代对象,要将其转换为列表,只需调用list()
内置函数:
list(cursor.fetchall())
请注意,可迭代对象通常与列表一样有用,而且由于它可以是惰性的,因此可能更有效。
你原来的代码失败了,因为它不太合理。你遍历行并枚举它们,所以你得到了(0, first_row), (1, second_row)
等等,这意味着你正在建立每个n行的第n个项目的列表,这根本不是你想要的。
这段代码显示了一些问题——首先,没有任何参数的list()
通常最好用空列表文字[]
替换,因为它更容易阅读。
接下来,你尝试通过索引进行循环遍历,在Python中这是一个坏主意。直接循环遍历值本身,而不是使用索引来获取值。
另外请注意,当你确实需要像这样构建值列表时,列表推导式是最好的方法,而不是创建一个列表,然后向其中添加元素。
cursor = connnect_db()
query = "SELECT * FROM `tbl`"
cursor.execute(query)
result = cursor.fetchall() //result = (1,2,3,) or result =((1,3),(4,5),)
final_result = [i[0] for i in result]
此外,最后两行可以合并为:
final_result = [i[0] for i in cursor.fetchall()]
cursor = connnect_db()
query = "SELECT * FROM `tbl`"
cursor.execute(query)
result = cursor.fetchall() //result = (1,2,3,) or result =((1,3),(4,5),)
final_result = [list(i) for i in result]
cursor = connection.cursor()
parameters = []
cursor.callproc('spProcedureName', parameters)
resultList =[r.fetchall() for r in cursor.stored_results()][0]
cursor.close()
import pymysql
# Create the database connection.
# The connection parameters are host, port, user, password, and database.
# These parameters in this code are held in the app.config().
dump_conn = pymysql.connect(
host=app.config[ 'DUMP_SQLALCHEMY_HOST' ],
port=int( app.config[ 'DUMP_SQLALCHEMY_PORT' ] ),
user=vault[ 'data' ][ 'username' ],
passwd=vault[ 'data' ][ 'password' ],
db=app.config[ 'DUMP_SQLALCHEMY_DB' ]
)
# Grab the query from a sql_queries helper file.
sql_query = query_transactions_for_csv()
# From the connection get a cursor.
dump_cursor = dump_conn.cursor()
# Handle the cursor.close() with a 'with' statement.
with dump_cursor as cursor:
# Execute the query.
cursor.execute( sql_query )
# Use list( cursor ) to get a Python list.
rows = list( cursor )