Python中的數據庫連接與查詢——使用SQLAlchemy


SQLAlchemy是Python用來操作數據庫的一個庫,該庫提供了SQL工具包及對象關系映射(ORM)工具。數據庫的記錄用Python的數據結構來表現,可以看做一個列表,每條記錄是列表中的一個元組。

SQLAlchemy基本用法

1)導入SQLAlchemy,並初始化DBSession

from sqlalchemy import Column, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
# 創建對象的基類
Base = declarative_base()
# 定義Product對象
class Product(Base):
    __tablename__ ='Product'
    ID = Column(String(20),primary_key=True)
    name = Column(String(20))
    class_name = Column(String(20))
        engine = create_engine('mysql+pymysql://root:password@localhost:3306/test')
        # 創建DBSession類型
        DBSession = sessionmaker(bind=engine)

  

2)向數據庫表中添加一行記錄

session = DBSession()
new_user = Product(ID = '19558276', name = '***', type = 'A')
session.add(new_user)
session.commit()

  

3)從數據庫表中查詢數據

student = session.query(Product).filter(Product.ID=='19558276').one() # 如果調用all()返回所有行
print('name:',student.name)
print('class_name:',student.class_name)

  

4)在數據庫表中更新數據

session.query(Product).filter(Product.ID='19558276').update({Product.name:"AAA"})
session.commit()

  

5)從數據庫表中刪除數據

session.query(Product).filter(Product.ID='19558276').delete()
session.commit()
session.close()

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM