紀錄了一下學習 SQLALchemy 的過程,如果有錯誤再請各位大神指教
pip install sqlalchemy
pip install pymysql # if need
註: sqlalchemy 會依賴於其他的 database module 進行操作
註: 若使用 sqlite 不需要另外安裝,python 內建就有包含
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
engine_url = "<url>"
engine = create_engine(engine_url, echo=True)
sqlite:///C:\\<path>\\test.db
mysql+pymysql://<username>:<password>@<host>:<port>/<database_name>
要特別注意 sqlalchemy 不允許修改表結構,如果需要修改的話,需要刪除重建
from sqlalchemy import Column
from sqlalchemy import Integer, String, DATETIME
class Test(Base):
__tablename__ = "test"
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(55))
time = Column(DATETIME)
註: Column 可以建立一個欄位
註: Integer, String, DATETIME, ...... 則為資料庫中常見的資料型態
def create_table():
Base.metadata.create_all(engine)
def drop_table():
Base.metadata.drop_all(engine)
if __name__ == '__main__':
drop_table()
create_table()
from sqlalchemy.orm import sessionmaker
def create_session():
Session = sessionmaker(bind=engine)
session = Session()
return session
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column
from sqlalchemy import Integer, String, DATETIME
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
engine_url = "<url>"
engine = create_engine(engine_url, echo=True)
class Test(Base):
__tablename__ = "test"
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(55))
time = Column(DATETIME)
def create_table():
Base.metadata.create_all(engine)
def drop_table():
Base.metadata.drop_all(engine)
def create_session():
Session = sessionmaker(bind=engine)
session = Session()
return session
if __name__ == '__main__':
drop_table()
create_table()