1. 程式人生 > >通過sqlalchemy操作mysql

通過sqlalchemy操作mysql

Coding user abc base ati 實例 對象 metadata maker

# 安裝 pip3 install sqlalchemy

import sqlalchemy

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,INTEGER,String
from sqlalchemy.orm import sessionmaker

# 創建連接
engine = create_engine("mysql+pymysql://root:[email protected]/testdb",encoding="utf-8",echo=True)

# 生成ORM基類
Base = declarative_base()

class User(Base):
__tablename__ = ‘user‘
id = Column(INTEGER,primary_key=True)
name = Column(String(32))
password = Column(String(64))

Base.metadata.create_all(engine) # 創建表結構

Session_class = sessionmaker(bind=engine) # 創建與數據庫連接會話的類
Session = Session_class() # 生成session實例 #cursor

user_obj = User(name="dennis",password="abc123") #生成要創建的數據對象
user_obj2 = User(name="alex",password="abcd")
print(user_obj.name,user_obj.id)
Session.add(user_obj)
Session.add(user_obj2)

Session.commit()

通過sqlalchemy操作mysql