Python使用sqlalchemy模塊連接數(shù)據(jù)庫操作示例
本文實例講述了Python使用sqlalchemy模塊連接數(shù)據(jù)庫操作。分享給大家供大家參考,具體如下:
安裝:
pip install sqlalchemy # 安裝數(shù)據(jù)庫驅(qū)動: 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語句信息
create_engine
接受一個url,格式為:
# '數(shù)據(jù)庫類型+數(shù)據(jù)庫驅(qū)動名稱://用戶名:口令@機器地址:端口號/數(shù)據(jù)庫名' # 常用的 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連接
簡單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語句等調(diào)試信息 session_maker = sessionmaker(bind=engine) session = session_maker() Base = declarative_base() #對應一張表 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子類對象作為參數(shù)外,還可以是字段,如:
query = session.query(Student.name, Student.age) # query為一個sqlalchemy.orm.query.Query對象 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()
方法返回單個結(jié)果。(若結(jié)果集為空則返回None)
print(queryObject.first()) # ('ns',)
one()
方法返回單個結(jié)果,與first()
方法不同的是:當結(jié)果集中沒有元素或有多于一個元素會拋出異常。
one_or_none()
方法同one()
一樣,不同是結(jié)果集為空則返回None,為多個拋出異常。
查詢數(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語句:
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ù)庫操作技巧匯總》、《Python數(shù)學運算技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
- python使用mysqldb連接數(shù)據(jù)庫操作方法示例詳解
- python連接數(shù)據(jù)庫的方法
- Python連接數(shù)據(jù)庫學習之DB-API詳解
- python mysqldb連接數(shù)據(jù)庫
- 跟老齊學Python之通過Python連接數(shù)據(jù)庫
- 學習python之編寫簡單簡單連接數(shù)據(jù)庫并執(zhí)行查詢操作
- Python 3.x 連接數(shù)據(jù)庫示例(pymysql 方式)
- Python使用Flask-SQLAlchemy連接數(shù)據(jù)庫操作示例
- 解決python3 Pycharm上連接數(shù)據(jù)庫時報錯的問題
- Python與數(shù)據(jù)庫交互:入門指南
相關(guān)文章
關(guān)于python的編碼與解碼decode()方法及zip()函數(shù)
這篇文章主要介紹了關(guān)于python的編碼與解碼decode()方法及zip()函數(shù),encode0?方法是字符串對象內(nèi)置的一個實現(xiàn)方法用于實現(xiàn)編碼操作,需要的朋友可以參考下2023-04-04使用memory_profiler監(jiān)測python代碼運行時內(nèi)存消耗方法
今天小編就為大家分享一篇使用memory_profiler監(jiān)測python代碼運行時內(nèi)存消耗方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12Python詳細對比講解break和continue區(qū)別
這篇文章主要介紹了python循環(huán)控制語句 break 與 continue,break就像是終止按鍵,不管執(zhí)行到哪一步,只要遇到break,不管什么后續(xù)步驟,直接跳出當前循環(huán)2022-06-06Python實現(xiàn)B站UP主自動監(jiān)控功能詳解
眾所周知,B站有很多有趣的UP主,可以教大家一些"實用"的知識,但是他們一般都沒有固定的更新時間。因此,本文將用Python編寫一個腳本,自動監(jiān)控UP是否更新了視頻,感興趣的可以了解一下2022-03-03一個基于flask的web應用誕生 用戶注冊功能開發(fā)(5)
一個基于flask的web應用誕生第五篇,這篇文章主要介紹了用戶注冊功能開發(fā),具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04