標籤:commit make python update ima mssql int char ext
#coding=utf-8from sqlalchemy import create_enginefrom sqlalchemy.orm import sessionmakerfrom sqlalchemy import Columnfrom sqlalchemy.types import CHAR, Integer, Stringfrom sqlalchemy.ext.declarative import declarative_baseBase=declarative_base()class Product(Base): __tablename__=‘Product‘ id = Column(String(20), primary_key=True) # 欄位 name = Column(String(20)) # 欄位 type= Column(String(20)) # 欄位 engine = create_engine(‘mssql+pymssql://sa:[email protected]:1433/world‘)#初始化資料庫連接DBSession=sessionmaker(bind=engine)#建立DBsesson類型Base.metadata.create_all(engine)#建立表結構#向資料庫寫入session=DBSession()#建立session對象new_user=Product(id=‘1233445‘,name=‘寧夏一日遊‘,type=‘景+酒‘)#建立新Product對象session.add(new_user)#添加到sessionsession.commit()#提交即儲存到資料庫#查詢#建立Query查詢。filter是where條件,最後調用one()返回唯一行,如果調用all()則返回所有行student=session.query(Product).filter(Product.id==‘1233445‘).one()#列印對象的name,class_name屬性print(‘name:‘,student.name)print(‘class_name:‘,student.type)#查詢並更新資料session.query(Product).filter(Product.id==‘1233445‘).update({Product.name:"寧夏中衛一日遊"})session.commit()#查詢並刪除資料session.query(Product).filter(Product.id=‘1233445‘).delete()session.commit()session.close()
python資料庫的增刪改查