SQLAlchemy是Python程式語言下的一款開源軟體。提供了SQL工具包及物件關係映射(ORM)工具,SQLAlchemy使用MIT許可證發行。它採用簡單的Python語音,為高效能和高效能的資料庫存取設計,實現了完整的企業級持久模型。 SQLAlchemy非常關注資料庫的量級和效能。
本節透過一套範例分析SQLAlchemy的使用方法。
使用SQLAlchemy至少需要3部分程式碼,它們分別是定義表、定義資料庫連線、進行增、刪、改、查等邏輯操作。
定義表的實例:
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column,Integer,String Base=declarative_base() class Accout(Base): __tablename__=u'accout' id=Column(Integer,primary_key=True) user_namr=Column(String(50),nullable=False) password=Column(String(200),nullable=False) title=Column(String(50)) salary=Column(Integer) def is_active(self): #假设所有 return True def get_id(self): #返回账号ID,用方法返回属性值提高了表的封装性。 return self.id def is_authenticated(self): #假设已经通过验证 return True def is_anonymous(self): #具有登陆名和密码的账号不是匿名用户 return False
解析定義表的程式碼如下:
SQLAlchemy表之前必須引入sqlalchemy .ext.declarative_base,並定義一個它的實例Base。所有表格必須繼承自Base。本例中定義了一個帳戶表類Account。
透過__tablename__屬性定義了資料表在資料庫中實際的名稱account。
引入sqlalchemy套件中的Column、Integer、String類型,因為需要用它們定義表中的欄位。本例在Account表中定義了5個欄位,分別是整數id和salary,以及字串類型的user_name、password、title。
在定義列時可以透過給Column傳送參數定義約束。本例中透過primary_key參數將id列定義主鍵,透過nullable參數將user__name和password定義非空。
在表中也可以自訂其他函數。本範例定義了使用者驗證時常用的幾個函數:is__activite()、get__id()、is__authenticate()和is_anonymous()。
定義資料庫連接的範例程式碼如下:
from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session,sessionmaker from contextlib import contextmanager db_connect_string='mysql://v_user:v_pase@localhost:3306/test_database?charset=utf8' ssl_args={ 'ssl':{ 'cert':'/home/ssl/client-cert.pem', 'key':'/home/shouse/ssl/client-key.pem', 'ca':'/home/shouse/ssl/ca-cert.pem' } } engine=create_engine(db_connect_string,connect_args=ssl_args) SessionType=scoped_session(sessionmaker(bind=engine,expire_on_commit=False)) def GetSession(): return SessionType() @contextmanager def session_scope(): session=GetSession() try: yield session session.commit() except: session.rollback() raise finally: session.close()
解析此連接資料部分的程式碼如下:
引入資料庫和會話引擎:sqlalchemy.create_engine、sqlalchemy.orm.scoped_session、sqlalchemy.orm.sessionmaker。
定義連接資料庫需要用到的資料庫字串。本例連接MySQL資料庫,字串格式為[databse_type]://[user_name]:[password]@[domain]:[port]/[database]?[parameters]。本例除了必須的連接訊息,也傳入了charset參數,指定以utf-8編碼方式解碼資料庫中的字串。
用create_engine建立資料庫引擎,如果資料庫開啟了SSL連結,則在此處需要傳入ssl客戶端憑證的檔案路徑。
用scoped_session(sessionmaker(bind=engine))建立會話類型SessionType,並定義函數GetSession()用以建立SessionType的實例。
至此,已經可以用GetSession()函數建立資料庫會話並進行資料庫操作了。但為了使之後的資料庫操作的程式碼能夠自動進行事務處理,本例中定義了上下文函數session_scope()。在Python中定義上下文函數的方法是為其加入contextlib套件中的contextmanager裝飾器。在上下文函數中執行以下邏輯:在函數開始時建立資料庫會話,此時會自動建立一個資料庫事務:當發生異常時回滾(rollback)事務;當退出時關閉(close)連線。關閉連線時會自動進行交易提交(commit)操作。
進行資料庫操作的程式碼:
from sqlalchemy import or_,orm def InsertAccount(user,passwd,title,salary): #新增操作 with session_scope() as session: account=orm.Account(user_name=user,passwd=passwd,title=title,salary=salary) session.add(account) def GetAccount(id=None,user_name=None): #查询操作 with session_scope() as session: return session.query(orm.Account).filter( or_(orm.Account.id==id,orm.Account.user_name=user_name) ).first() def DeleteAccount(user_name): #删除操作 with session_scope() as session: account=GetAccount(user_name=user_name) if account: session.delete(account) def UpdateAccount(id,user_name,password,title,salary): #更新操作 with session_scope() as session: account=session.query(orm.Account).filter(orm.Account.id==id).first() if not account:return account.user_name=user_name account.password=password account.salary=salary account.title=title InsertAccount("Mark","123","Manager",3000) #调用新增操作 InsertAccount("帅哥","456","Boss",2000) #调用新增操作 GetAccount(2) #调用查询操作 DeleteAccount("Mark") UpdateAccount(1,"admin","none","System admin",2500)
本範例示範了資料庫中最常用的4種基於記錄的操作:新增、尋找、刪除、更新。對此部分程式碼的解析如下:
用import語句引入資料表(Account)所在的套件orm。引入多條件查詢時使用or_。
每個函數中都透過with語句啟用上下文函數session_scope(),透過它取得到session對象,並自動開啟新事物。
在InsertAccount中,透過新建一個表格Account實例,並透過session.add將其新增至資料庫。由於上下文函數退出時會自動提交事務,所以無需顯示的呼叫session.commit()使新增生效。
在GetAccount中透過query語句進行查詢,查詢條件由filter設置,多個查詢條件可以用or_或and_連接。
在DeleteAccount中透過GetAccount查詢該對象,如果查詢到了,則直接呼叫session.delete()將該物件刪除。
在InsertAccount()中透過query根據id查詢記錄,如果查詢到了,則透過設定物件的屬性來實現對記錄的修改。
查詢語句的結果是一個物件集合。查詢語句後面的first()函數用於提取該集合中的第一個對象,如果用all()函數替換first()函數,則查詢會傳回該集合。
主流資料庫的連接方式
SQLAlchemy這樣的orm資料庫操作方式可以對業務開發者屏蔽不同資料庫之間的差異,這樣當需要進行資料庫遷移時(例如MySQL遷移到SQLite),則只需要更換資料庫連接字串。
下表列出了SQLAlchemy連接主流資料庫時的資料庫字串的編寫方法:
資料庫 | 連接字串 |
---|---|
#Microsoft SQLServer | 'mssql pymssql://[用戶]:[密碼]@[網域]:[連接埠]/[資料庫名稱]' |
MySQL | 'mysql://[使用者]:[密碼]@[網域]:[連接埠]/[資料庫名稱]' |
#Oracle | 'oracle://[使用者]:[密碼]@ [網域]:[連接埠/[資料庫名稱]]' |
PostgreSQL | 'postgresql://[使用者]:[密碼]@[網域] :[連接埠]/[資料庫名稱]' |
SQLite | 'sqlite://[檔案路徑名]' |
以上是Python下SQLAlchemy的簡單介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

你可以通過使用pyenv、venv和Anaconda來管理不同的Python版本。 1)使用pyenv管理多個Python版本:安裝pyenv,設置全局和本地版本。 2)使用venv創建虛擬環境以隔離項目依賴。 3)使用Anaconda管理數據科學項目中的Python版本。 4)保留系統Python用於系統級任務。通過這些工具和策略,你可以有效地管理不同版本的Python,確保項目順利運行。

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基於基於duetoc的iMplation,2)2)他們的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函數函數函數函數構成和穩定性構成和穩定性的操作,製造

數組的同質性對性能的影響是雙重的:1)同質性允許編譯器優化內存訪問,提高性能;2)但限制了類型多樣性,可能導致效率低下。總之,選擇合適的數據結構至關重要。

到CraftCraftExecutablePythcripts,lollow TheSebestPractices:1)Addashebangline(#!/usr/usr/bin/envpython3)tomakethescriptexecutable.2)setpermissionswithchmodwithchmod xyour_script.3)

numpyArraysareAreBetterFornumericalialoperations andmulti-demensionaldata,而learthearrayModuleSutableforbasic,內存效率段

numpyArraySareAreBetterForHeAvyNumericalComputing,而lelethearRayModulesiutable-usemoblemory-connerage-inderabledsswithSimpleDatateTypes.1)NumpyArsofferVerverVerverVerverVersAtility andPerformanceForlargedForlargedAtatasetSetsAtsAndAtasEndCompleXoper.2)

ctypesallowscreatingingangandmanipulatingc-stylarraysinpython.1)usectypestoInterfacewithClibrariesForperfermance.2)createc-stylec-stylec-stylarraysfornumericalcomputations.3)passarraystocfunctions foreforfunctionsforeffortions.however.however,However,HoweverofiousofmemoryManageManiverage,Pressiveo,Pressivero


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

WebStorm Mac版
好用的JavaScript開發工具

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

記事本++7.3.1
好用且免費的程式碼編輯器