sqlAlchemy例項操作

2021-10-08 04:33:59 字數 2099 閱讀 8499

from sqlalchemy import create_engine

from sqlalchemy.ext.declarative import declarative_base

from sqlalchemy import column, string, integer, float

from sqlalchemy.orm import sessionmaker

# 資料庫連線配置

host = mysql_config.get("host", 'localhost')

port = mysql_config.get("port", 3306)

user = mysql_config.get("user", "root")

pass_wd = mysql_config.get("passwd", "123456")

db_name = mysql_config.get("dbname", "pdd")

engine = create_engine(f"mysql+pymysql://:@:/?charset=utf8")

base = declarative_base()

class tradingsituationmodel(base):

# 表模型 用來定義字段

# __tablename__ 定義要建立的表名 comment 字段注釋

__tablename__ = "spt_trading_situation"

id = column(integer, primary_key=true)

company_name = column("company_name", string(54), comment="公司名")

shop_keeper = column("shop_keeper", string(54), comment="店長")

shop_url = column("shop_url", string(54), comment="店鋪url")

crawl_time = column("crawl_time", string(64),comment="採集時間")

created_at = column("created_at", integer,comment="建立時間")

updated_at = column("updated_at", integer,comment="更新時間")

is_deleted = column("is_deleted", integer,comment="軟刪除 1 是 0 否")

class tradingsituationmanager():

def __init__(self):

session = sessionmaker(bind=engine) # 建立會話物件 用於資料表的操作

self.model = tradingsituationmodel

self.session = session()

base.metadata.create_all(engine)

def handle_result(self, item):

try:

filter = self.session.query(self.model).filter_by(

shop_id=item["shop_id"], # 這裡填寫過濾條件

)filter_res = filter.first()

if filter_res:

# 如果存在索引字段查詢的資料 就更新資料 不需要更新的字段這裡直接pop掉即可

for key in item:

setattr(filter_res, key, item[key])

else:

# 資料不存在索引字段插敘你的資料,新增一條資料

jobs = self.model(**item)

self.session.add(jobs)

# 可以設定是否自動提交

self.session.commit()

except:

traceback.print_exc()

self.session.rollback()

sqlalchemy基本操作

sqlalchemy的簡單實用 其他比較好的人寫的 各種基本操作 sqlalchemy指南 常用技巧 usr bin env python coding utf 8 from sqlalchemy import column,string,create engine,metadata from sq...

SQLAlchemy操作MariaDB筆記之三

query方法返回的是乙個可迭代輸出的物件,可以索引和切片。引數可以為表物件,表的字段物件。for instance in session.query user order by user.id print instance.name,instance.fullname for name,fulln...

SQLAlchemy基礎操作二

usr bin env python coding utf 8 import time import threading from sqlalchemy.ext.declarative import declarative base from sqlalchemy import column,int...