欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python使用sqlalchemy模塊連接數(shù)據(jù)庫操作示例

 更新時間:2019年03月13日 11:17:15   作者:xuejianbest  
這篇文章主要介紹了Python使用sqlalchemy模塊連接數(shù)據(jù)庫操作,結(jié)合實例形式分析了sqlalchemy模塊的安裝及連接、調(diào)用數(shù)據(jù)庫相關(guān)操作技巧,需要的朋友可以參考下

本文實例講述了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()
#對應(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子類對象作為參數(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()方法不同的是:當(dāng)結(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ù)學(xué)運算技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總

希望本文所述對大家Python程序設(shè)計有所幫助。

相關(guān)文章

  • Python實現(xiàn)合并PDF文件的三種方式

    Python實現(xiàn)合并PDF文件的三種方式

    在處理多個 PDF 文檔時,頻繁地打開關(guān)閉文件會嚴重影響效率,因此我們可以先將這些PDF文件合并起來再操作,本文將分享3種使用 Python 合并 PDF 文件的實現(xiàn)方法,希望對大家有所幫助
    2023-11-11
  • 關(guān)于python的編碼與解碼decode()方法及zip()函數(shù)

    關(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)存消耗方法

    今天小編就為大家分享一篇使用memory_profiler監(jiān)測python代碼運行時內(nèi)存消耗方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-12-12
  • Python機器視覺之基于OpenCV的手勢檢測

    Python機器視覺之基于OpenCV的手勢檢測

    這篇文章主要為大家介紹了一個機器視覺項目:基于OpenCV的手勢檢測,文中的示例代碼講解詳細,對我們學(xué)習(xí)Python和OpenCV有一定的幫助,感興趣的可以跟隨小編學(xué)習(xí)一下
    2021-12-12
  • python實戰(zhàn)小游戲之考驗記憶力

    python實戰(zhàn)小游戲之考驗記憶力

    本篇文章介紹了用python編寫的曾經(jīng)風(fēng)靡的考驗記憶力的小游戲,詳細介紹了整個思路和過程以及代碼,通讀本篇對大家的學(xué)習(xí)或工作具有一定的價值,需要的朋友可以參考下
    2021-09-09
  • Python計算點到直線距離、直線間交點夾角

    Python計算點到直線距離、直線間交點夾角

    這篇文章主要介紹了Python計算點到直線距離、直線間交點夾角,需要的朋友可以參考下
    2021-12-12
  • Python詳細對比講解break和continue區(qū)別

    Python詳細對比講解break和continue區(qū)別

    這篇文章主要介紹了python循環(huán)控制語句 break 與 continue,break就像是終止按鍵,不管執(zhí)行到哪一步,只要遇到break,不管什么后續(xù)步驟,直接跳出當(dāng)前循環(huán)
    2022-06-06
  • Python實現(xiàn)B站UP主自動監(jiān)控功能詳解

    Python實現(xiàn)B站UP主自動監(jiān)控功能詳解

    眾所周知,B站有很多有趣的UP主,可以教大家一些"實用"的知識,但是他們一般都沒有固定的更新時間。因此,本文將用Python編寫一個腳本,自動監(jiān)控UP是否更新了視頻,感興趣的可以了解一下
    2022-03-03
  • 一個基于flask的web應(yīng)用誕生 用戶注冊功能開發(fā)(5)

    一個基于flask的web應(yīng)用誕生 用戶注冊功能開發(fā)(5)

    一個基于flask的web應(yīng)用誕生第五篇,這篇文章主要介紹了用戶注冊功能開發(fā),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-04-04
  • python中np是做什么的

    python中np是做什么的

    在本篇內(nèi)容里小編給大家整理的是一篇關(guān)于python中np的作用的相關(guān)文章,有興趣的朋友們跟著學(xué)習(xí)下。
    2020-07-07

最新評論