sqlalchemy 查詢:指定字段名問題
在 sqlalchemy 中執行查詢時,用戶可能會遇到指定字段名的要求。這與其他編程語言(如 php)不同,在 php 中可以直接使用 sql 查詢。
修改后的代碼片段:
from sqlalchemy import text, create_engine engine = create_engine("mysql+pymysql://賬號:密碼@地址/庫") with engine.connect() as connection: result = connection.execute(text("select username from users")) for row in result: print("username:", row.username)
登錄后復制
在以上代碼片段中,我們使用 text() 函數來構造 sql 查詢,該函數允許我們指定要查詢的字段名。在 result 循環中,我們使用 row.username 訪問結果行的指定列。
官方文檔:
更多詳細信息,請參閱 sqlalchemy 官方文檔:https://docs.sqlalchemy.org/en/20/core/connections.html(與問題答案提供的鏈接相同)。