Python使用sqlalchemy模塊連接數(shù)據(jù)庫(kù)操作示例
本文實(shí)例講述了Python使用sqlalchemy模塊連接數(shù)據(jù)庫(kù)操作。分享給大家供大家參考,具體如下:
安裝:
pip install sqlalchemy # 安裝數(shù)據(jù)庫(kù)驅(qū)動(dòng): pip install pymysql pip install cx_oracle
舉例:(在url后面加入?charset=utf8可以防止亂碼)
from sqlalchemy import create_engine engine=create_engine('mysql+pymysql://username:password@hostname:port/dbname', echo=True) #echo=True 打印sql語(yǔ)句信息
create_engine
接受一個(gè)url,格式為:
# '數(shù)據(jù)庫(kù)類型+數(shù)據(jù)庫(kù)驅(qū)動(dòng)名稱://用戶名:口令@機(jī)器地址:端口號(hào)/數(shù)據(jù)庫(kù)名' # 常用的 engine = create_engine('sqlite:///:memory:', echo=True) # sqlite內(nèi)存 engine = create_engine('sqlite:///./cnblogblog.db',echo=True) # sqlite文件 engine = create_engine("mysql+pymysql://username:password@hostname:port/dbname",echo=True) # mysql+pymysql engine = create_engine('mssql+pymssql://username:password@hostname:port/dbname',echo=True) # mssql+pymssql engine = create_engine('postgresql://scott:tiger@hostname:5432/dbname') # postgresql示例 engine = create_engine('oracle://scott:tiger@hostname:1521/sidname') # oracle engine = create_engine('oracle+cx_oracle://scott:tiger@tnsname') #pdb就可以用tns連接
簡(jiǎn)單demo:
from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base engine = create_engine('oracle://spark:a@orclpdb',echo=True) #echo要求打印sql語(yǔ)句等調(diào)試信息 session_maker = sessionmaker(bind=engine) session = session_maker() Base = declarative_base() #對(duì)應(yīng)一張表 class Student(Base): __tablename__ = 'STUDENT' id = Column('STUID', Integer, primary_key=True) name = Column('STUNAME', String(32), nullable=False) age = Column('STUAGE', Integer) def __repr__(self): return '<Student(id:%s, name:%s, age:%s)>' % (self.id, self.name, self.age) Base.metadata.create_all(engine) #若存在STUDENT表則不做,不存在則創(chuàng)建。 queryObject = session.query(Student).order_by(Student.id.desc()) for ins in queryObject: print(ins.id, ins.name, ins.age) ''' 4 hey 24 3 lwtxxs 27 2 gyb 89 1 ns 23 '''
將查詢結(jié)果映射為DataFrame:
import pandas as pd df = pd.read_sql(session.query(Student).filter(Student.id > 1).statement, engine) print(df) ''' STUID STUNAME STUAGE 0 4 hey 24 1 2 gyb 89 2 3 lwtxxs 27 '''
查詢:
session的query方法除了可以接受Base子類對(duì)象作為參數(shù)外,還可以是字段,如:
query = session.query(Student.name, Student.age) # query為一個(gè)sqlalchemy.orm.query.Query對(duì)象 for stu_name, stu_age in query: print(stu_name, stu_age)
查詢條件filter:
# = / like query.filter(Student.name == 'wendy') query.filter(Student.name.like('%ed%')) # in query.filter(Student.name.in_(['wendy', 'jack'])) query.filter(Student.name.in_( session.query(User.name).filter(User.name.like('%ed%')) )) # not in query.filter(~Student.name.in_(['ed', 'wendy', 'jack'])) # is null / is not null query.filter(Student.name == None) query.filter(Student.name.is_(None)) query.filter(Student.name != None) query.filter(Student.name.isnot(None)) # and from sqlalchemy import and_, or_ query.filter(and_(Student.name == 'ed', Student.age != 23)) query.filter(Student.name == 'ed', Student.age != 23) query.filter(Student.name == 'ed').filter(Student.age != 23) # or query.filter(or_(Student.name == 'ed', Student.name == 'wendy')) # match query.filter(Student.name.match('wendy'))
Query的方法:
all()
方法以列表形式返回結(jié)果集:
from sqlalchemy import or_, and_ queryObject = session.query(Student).filter(or_(Student.id == 1, Student.id == 2)) print(queryObject.all()) # [<Student(id:1, name:ns, age:23)>, <Student(id:2, name:gyb, age:89)>] queryObject = session.query(Student.name).filter(or_(Student.id == 1, Student.id == 2)) print(queryObject.all()) # [('ns',), ('gyb',)]
first()
方法返回單個(gè)結(jié)果。(若結(jié)果集為空則返回None)
print(queryObject.first()) # ('ns',)
one()
方法返回單個(gè)結(jié)果,與first()
方法不同的是:當(dāng)結(jié)果集中沒有元素或有多于一個(gè)元素會(huì)拋出異常。
one_or_none()
方法同one()
一樣,不同是結(jié)果集為空則返回None,為多個(gè)拋出異常。
查詢數(shù)量:
from sqlalchemy import func session.query(func.count(Student.id)).scalar() # SELECT count("STUDENT"."STUID") AS count_1 FROM "STUDENT"
分組:
session.query(func.count(Student.id), Student.name).group_by(Student.name).all()
嵌套SQL語(yǔ)句:
from sqlalchemy import text query = session.query(Student.id, Student.name).filter(text('stuid>2')) query = session.query('stuid', 'stuname', 'stuage').from_statement(\ text("select * from student where stuname=:stuname")).params(stuname='hey').all() #[(4, 'hey', 24)]
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python常見數(shù)據(jù)庫(kù)操作技巧匯總》、《Python數(shù)學(xué)運(yùn)算技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
- python使用mysqldb連接數(shù)據(jù)庫(kù)操作方法示例詳解
- python連接數(shù)據(jù)庫(kù)的方法
- Python連接數(shù)據(jù)庫(kù)學(xué)習(xí)之DB-API詳解
- python mysqldb連接數(shù)據(jù)庫(kù)
- 跟老齊學(xué)Python之通過(guò)Python連接數(shù)據(jù)庫(kù)
- 學(xué)習(xí)python之編寫簡(jiǎn)單簡(jiǎn)單連接數(shù)據(jù)庫(kù)并執(zhí)行查詢操作
- Python 3.x 連接數(shù)據(jù)庫(kù)示例(pymysql 方式)
- Python使用Flask-SQLAlchemy連接數(shù)據(jù)庫(kù)操作示例
- 解決python3 Pycharm上連接數(shù)據(jù)庫(kù)時(shí)報(bào)錯(cuò)的問題
- Python與數(shù)據(jù)庫(kù)交互:入門指南
相關(guān)文章
Python實(shí)現(xiàn)合并PDF文件的三種方式
在處理多個(gè) PDF 文檔時(shí),頻繁地打開關(guān)閉文件會(huì)嚴(yán)重影響效率,因此我們可以先將這些PDF文件合并起來(lái)再操作,本文將分享3種使用 Python 合并 PDF 文件的實(shí)現(xiàn)方法,希望對(duì)大家有所幫助2023-11-11關(guān)于python的編碼與解碼decode()方法及zip()函數(shù)
這篇文章主要介紹了關(guān)于python的編碼與解碼decode()方法及zip()函數(shù),encode0?方法是字符串對(duì)象內(nèi)置的一個(gè)實(shí)現(xiàn)方法用于實(shí)現(xiàn)編碼操作,需要的朋友可以參考下2023-04-04使用memory_profiler監(jiān)測(cè)python代碼運(yùn)行時(shí)內(nèi)存消耗方法
今天小編就為大家分享一篇使用memory_profiler監(jiān)測(cè)python代碼運(yùn)行時(shí)內(nèi)存消耗方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-12-12Python機(jī)器視覺之基于OpenCV的手勢(shì)檢測(cè)
這篇文章主要為大家介紹了一個(gè)機(jī)器視覺項(xiàng)目:基于OpenCV的手勢(shì)檢測(cè),文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)Python和OpenCV有一定的幫助,感興趣的可以跟隨小編學(xué)習(xí)一下2021-12-12python實(shí)戰(zhàn)小游戲之考驗(yàn)記憶力
本篇文章介紹了用python編寫的曾經(jīng)風(fēng)靡的考驗(yàn)記憶力的小游戲,詳細(xì)介紹了整個(gè)思路和過(guò)程以及代碼,通讀本篇對(duì)大家的學(xué)習(xí)或工作具有一定的價(jià)值,需要的朋友可以參考下2021-09-09Python計(jì)算點(diǎn)到直線距離、直線間交點(diǎn)夾角
這篇文章主要介紹了Python計(jì)算點(diǎn)到直線距離、直線間交點(diǎn)夾角,需要的朋友可以參考下2021-12-12Python詳細(xì)對(duì)比講解break和continue區(qū)別
這篇文章主要介紹了python循環(huán)控制語(yǔ)句 break 與 continue,break就像是終止按鍵,不管執(zhí)行到哪一步,只要遇到break,不管什么后續(xù)步驟,直接跳出當(dāng)前循環(huán)2022-06-06Python實(shí)現(xiàn)B站UP主自動(dòng)監(jiān)控功能詳解
眾所周知,B站有很多有趣的UP主,可以教大家一些"實(shí)用"的知識(shí),但是他們一般都沒有固定的更新時(shí)間。因此,本文將用Python編寫一個(gè)腳本,自動(dòng)監(jiān)控UP是否更新了視頻,感興趣的可以了解一下2022-03-03一個(gè)基于flask的web應(yīng)用誕生 用戶注冊(cè)功能開發(fā)(5)
一個(gè)基于flask的web應(yīng)用誕生第五篇,這篇文章主要介紹了用戶注冊(cè)功能開發(fā),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-04-04