from sqlalchemy import create_engine, Column, String, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# 建表
Base = declarative_base()
class Nodes(Base):
# 表名
__tablename__ = 'nodes'
# 定義字段
# {id: 0, type: 'python', category: 0, name: '定義', title: '變量'},
id = Column(Integer, primary_key=True, autoincrement=True)
type = Column(String(32))
category = Column(Integer)
name = Column(String(32))
title = Column(String(32))
engine = create_engine('sqlite:///nodes.db?check_same_thread=False', echo=True)
# 建表
# Nodes.__table__.create(engine, checkfirst=True)
# 創建會話
Session = sessionmaker(bind=engine)
session = Session()
# 單條數據
# node1 = Nodes(id=0, type='python', category=0, name='定義', title='變量')
# 插入多條數據
# nodes = [
# {'id': 1, 'type': 'python', 'category': 0, 'name': '調用', 'title': '變量'},
# {'id': 2, 'type': 'python', 'category': 0, 'name': '命名', 'title': '變量'},
# {'id': 3, 'type': 'python', 'category': 1, 'name': '定義', 'title': '函數'},
# {'id': 4, 'type': 'python', 'category': 2, 'name': '類的定義', 'title': '類'},
# {'id': 5, 'type': 'python', 'category': 3, 'name': '對象的定義', 'title': '對象'},
# {'id': 6, 'type': 'python', 'category': 3, 'name': '對象的屬性', 'title': '對象'}
# ]
#
# for node in nodes:
# id_ = node.get('id')
# type_ = node.get('type')
# category = node.get('category')
# name = node.get('name')
# title = node.get('title')
# 插入數據
# session.add(Nodes(id=id_, type=type_, category=category, name=name, title=title))
# 提交
# session.commit()
# 查詢數據
# items = session.query(Nodes).filter(Nodes.title == '變量').all()
items = session.query(Nodes).all()
nodes_list = []
for item in items:
temp_item = {
'id': item.id,
'type': item.type,
'category': item.category,
'name': item.name,
'title': item.title
}
nodes_list.append(temp_item)
print(nodes_list)
sqlalchemy操作數據庫
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.