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