使用 sqlalchemy 查詢數(shù)據(jù)庫(kù)
在使用 sqlalchemy 進(jìn)行數(shù)據(jù)庫(kù)查詢時(shí),是否必須指定字段名?
解答:
使用 sqlalchemy 查詢數(shù)據(jù)庫(kù)時(shí),新版代碼中不再需要單獨(dú)指定字段名。您可以像 php 一樣直接書(shū)寫(xiě) sql 語(yǔ)句,如下所示:
from sqlalchemy import text, create_engine engine = create_engine("mysql+pymysql://賬號(hào):密碼@地址/庫(kù)") with engine.connect() as connection: result = connection.execute(text("select username from users")) for row in result: print("username:", row.username)
注意:
以上代碼是新版代碼,與老版代碼不同之處在于使用了 text() 函數(shù)來(lái)執(zhí)行 sql 語(yǔ)句,它允許您直接編寫(xiě) sql 而無(wú)需顯式指定字段名。
有關(guān)詳細(xì)信息,請(qǐng)參閱 sqlalchemy 官方文檔:https://docs.sqlalchemy.org/en/20/core/connections.html
? 版權(quán)聲明
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載。
THE END