本文實例講述了Python流行ORM框架sqlalchemy安裝與使用。分享給大家供大家參考,具體如下:
安裝
http://docs.sqlalchemy.org
1、安裝
#進入虛擬環(huán)境 #執(zhí)行 ./python3 -m pip install
import sqlalchemy print(sqlalchemy.__version__) # 1.1.15
我這里使用的版本是1.1.15
創(chuàng)建連接對象
http://docs.sqlalchemy.org/en/latest/orm/tutorial.html#connecting
from sqlalchemy import create_engine # 連接本地test數(shù)據(jù)庫 engine = create_engine("mysql://root:root@localhost/test?charset=utf8")
運行時會出錯,因為需要驅(qū)動庫,默認會調(diào)用MySQLdb。
ImportError: No module named 'MySQLdb'
我們前面安裝了pymysql,因此完整的要這么寫:
engine = create_engine("mysql+pymysql://root:root@localhost/test?charset=utf8")
簡單使用
SQL語句查詢
result = engine.execute("select * from news") print(result.fetchall()) #[(1, '本機新聞標題'), (2, '今天的新聞'), (3, '新聞標題1'), (4, '新聞標題2'), (5, '元組新聞1'), (6, '元組新聞2')]
創(chuàng)建映射
既然我們用ORM,就是為了少寫甚至不寫SQL語句。
ORM是數(shù)據(jù)表和對象之間的映射。
http://docs.sqlalchemy.org/en/latest/orm/tutorial.html#declare-a-mapping
1、創(chuàng)建一個Infos.py文件,這個文件我們來做數(shù)據(jù)表的映射
from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() from sqlalchemy import Column, Integer, String class News(Base): # 表名稱 __tablename__ = 'news' # news表里id字段 id = Column(Integer, primary_key=True, autoincrement=True) # news表里title字段 title = Column(String(length=255), nullable=False)
News類就是我們數(shù)據(jù)表news的映射(字段:id、title)。
2、使用
from sqlalchemy import create_engine from mappers.Infos import News from sqlalchemy.orm import sessionmaker # 連接本地test數(shù)據(jù)庫 engine = create_engine("mysql+pymysql://root:root@localhost/test?charset=utf8") # 創(chuàng)建會話 session = sessionmaker(engine) mySession = session() # 查詢結(jié)果集 result = mySession.query(News).all() print(result[0])
我們要注意最后的查詢結(jié)果,看看結(jié)果集中的元素長什么樣?^_^
查詢處理的記錄都是對象。
各種查詢
只查詢第一條記錄
# 查詢第一條 result = mySession.query(News).first() print(result.title) #打印對象屬性
通過id字段查詢
# 查詢id為2的 result = mySession.query(News).filter_by(id=2).first() print(result.title)
# 查詢id為2的 result = mySession.query(News).filter(News.id==2).first()
分頁查詢
# 分頁查詢 0,2 result = mySession.query(News).filter(News.id>1).limit(2).offset(0).all() print(result)
自定義過濾條件
# 自定義過濾條件 result = mySession.query(News).filter(text("id>:id")).params(id=2).all()
根據(jù)主鍵查詢
result = mySession.query(News).get(3) print(result.title)
新增和修改
# 新增 news = News(title="新增測試標題") mySession.add(news) mySession.commit()
#修改 mySession.query(News).filter(News.id==7).update({"title":"修改之后的標題"}) mySession.commit()
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python常見數(shù)據(jù)庫操作技巧匯總》、《Python數(shù)學(xué)運算技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
