python操作數(shù)據(jù)庫基礎(chǔ)知識

python是如何訪問數(shù)據(jù)庫的,通過數(shù)據(jù)庫接口DB-API,他是闡明一系列所需對象和數(shù)據(jù)庫訪問機(jī)制的標(biāo)準(zhǔn),它可以為不同的數(shù)據(jù)庫適配器和底層數(shù)據(jù)庫系統(tǒng)提供一致性的訪問。

為實(shí)現(xiàn)對數(shù)據(jù)庫的訪問,python開發(fā)了許多用于連接數(shù)據(jù)庫的適配器。
以mysql為例,python3中可以使用 mysql-connector-python 以及 pymysql。

與數(shù)據(jù)庫交互的方式有兩種,一種是簡單直接的原始sql語句,另一種就是ORM(假如你更愿意操作python對象的話,這是更好的選擇)

1、原生sql

  import 適配器
  connect 方法連接數(shù)據(jù)庫,返回connect對象
  生成該connect的游標(biāo)對象
  cur = connect.cursor()
  調(diào)用方法進(jìn)行數(shù)據(jù)庫增刪改查
  callpro execute 常用
  關(guān)閉連接

2、ORM

sqallchemy是比較流行的pytho ORM,支持python3+,安裝方式也很簡單。最好的教程([http://docs.sqlalchemy.org/en/latest/orm/tutorial.html]

我力求用最簡單的語言來說一下它的基本用法。

orm就是建立數(shù)據(jù)庫的映射對象。通過sqlalchemy的內(nèi)置declarative_base方法,完成與數(shù)據(jù)庫表的映射。

import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import String, Integer, Column
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship,sessionmaker
#首先連接數(shù)據(jù)庫,echo=True,讓你在命令窗口執(zhí)行的時候,可以查看生成的原生SQL的樣子
engine = create_engine('mysql+mysqlconnector://user:psw@ip/dbname',echo=True)

Base = declarative_base()
#繼承Base,將users表映射為User對象
class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True, nullable=True)
    name = Column(String(20))
    newpassword = Column(String(20))
    getpassword = Column(String(20))
    addresses = relationship("Address", back_populates="user")#與Address建立relationship
    def __repr__(self):  #命令窗口調(diào)試用
        return "<User(name='%s', id='%s')>" % (
            self.name, self.id)

class Address(Base):
    __tablename__ = 'address'
    id = Column(Integer, primary_key=True, nullable=True)
    email_address = Column(String(50))
    userid = Column(Integer,ForeignKey('test.id')) #建立外鍵
    user = relationship("User", back_populates="addresses")
    def __repr__(self):
        return "<Address(email_address='%s')>" % self.email_address

   jack = User(name='ttt',newpassword='123',getpassword='123')
    jack.addresses=[Address(email_address='111111'),Address(email_address='222222')]
    Session = sessionmaker(bind=engine) #建立session . The ORM’s “handle” to the database is the Session

    session = Session()
    session.add(jack) #添加對象
    session.commit() #提交之前數(shù)據(jù)庫是不會發(fā)生變化的。需要flush
    jack = session.query(User).filter_by(name='ttt').one() #查詢
    session.query(User).join(Address) #交叉查詢 join 深入了解可以去看那篇文章
    print(jack)
    print(jack.addresses)
#如何使用存儲過程
#創(chuàng)建存儲過程小細(xì)節(jié),在用命令行時,利用delimiter $$來更改默認(rèn);結(jié)束執(zhí)行
#Calling Stored Procedures
    connection = engine.raw_connection() #獲取原生連接
    try:
        cursor = connection.cursor()
        #無參數(shù)
        cursor.callproc('find_test')
        for i in cursor.stored_results(): #結(jié)果都存在stored_results()函數(shù)中
            print(i.fetchall())
        cursor.close()
        cursor = connection.cursor()
        # 有參數(shù)
        args=['guhongye',0]#輸出參數(shù)可以用0來占位
        result = cursor.callproc('find_test1',args=args)
        print(result[1])
        cursor.close()
    finally:
        connection.close()

3、alembic

alembic簡明教程,下面這篇文章講的很詳細(xì)
http://huangx.in/18/alembic-simple-tutorial

1.alembic init YOUR_ALEMBIC_DIR
2.alembic revision -m "create account table"
#自動更新 env.py 17行做如下修改
import os
import sys
root = os.path.dirname(__file__)+'/../' # 定位到project根目錄
sys.path.append(root)
from learnsqlalchemy import Base
target_metadata = Base.metadata
#可按下面執(zhí)行
  alembic revision  --autogenerate -m "create account table"
3.alembic upgrade head
4.alembic downgrade 版本號
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容