今天就跟大家聊聊有關如何在Python中使用sqlalchemy模塊連接數(shù)據(jù)庫,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據(jù)這篇文章可以有所收獲。
公司主營業(yè)務:成都網(wǎng)站設計、做網(wǎng)站、成都外貿網(wǎng)站建設公司、移動網(wǎng)站開發(fā)等業(yè)務。幫助企業(yè)客戶真正實現(xiàn)互聯(lián)網(wǎng)宣傳,提高企業(yè)的競爭能力。創(chuàng)新互聯(lián)建站是一支青春激揚、勤奮敬業(yè)、活力青春激揚、勤奮敬業(yè)、活力澎湃、和諧高效的團隊。公司秉承以“開放、自由、嚴謹、自律”為核心的企業(yè)文化,感謝他們對我們的高要求,感謝他們從不同領域給我們帶來的挑戰(zhàn),讓我們激情的團隊有機會用頭腦與智慧不斷的給客戶帶來驚喜。創(chuàng)新互聯(lián)建站推出下城免費做網(wǎng)站回饋大家。安裝:
pip install sqlalchemy # 安裝數(shù)據(jù)庫驅動: 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ù)庫驅動名稱://用戶名:口令@機器地址:端口號/數(shù)據(jù)庫名' # 常用的 engine = create_engine('sqlite:///:memory:', echo=True) # sqlite內存 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語句等調試信息 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 '' % (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 '''
將查詢結果映射為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()
方法以列表形式返回結果集:
from sqlalchemy import or_, and_ queryObject = session.query(Student).filter(or_(Student.id == 1, Student.id == 2)) print(queryObject.all()) # [, ] queryObject = session.query(Student.name).filter(or_(Student.id == 1, Student.id == 2)) print(queryObject.all()) # [('ns',), ('gyb',)]
first()
方法返回單個結果。(若結果集為空則返回None)
print(queryObject.first()) # ('ns',)
one()
方法返回單個結果,與first()
方法不同的是:當結果集中沒有元素或有多于一個元素會拋出異常。one_or_none()
方法同one()
一樣,不同是結果集為空則返回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)]
看完上述內容,你們對如何在Python中使用sqlalchemy模塊連接數(shù)據(jù)庫有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。