sqlalchemy 對查詢結果的指定
sqlalchemy 在查詢時是否必須指定字段名呢?
官方文檔表明,新版 sqlalchemy 代碼中,可以使用 text 函數來執行 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(“select username from users”) 創建了一個文本表達式,它表示要執行的 sql 查詢。我們不再需要手動指定字段名,而是可以通過 row.username 訪問結果中的值。
與舊版代碼相比,新版代碼更加簡潔明了,同時它也提供了更多的靈活性。更多信息,請參閱官方文檔。
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END