推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
1800x
V2EX  ›  Python

如何通过 sqlalchemy 实现 go 语言 sqlx 中的模型效果:查询结果填充 和 查询参数绑定

  •  
  •   1800x · Apr 13, 2019 · 2682 views
    This topic created in 2731 days ago, the information mentioned may be changed or developed.
    例如有下面的模型:
    type Person struct {
    FirstName string `db:"first_name"`
    LastName string `db:"last_name"`
    }

    查询结果填充
    jason = Person{}
    err = db.Get(&jason, "SELECT * FROM person WHERE first_name=$1", "Jason")
    Get 会将查询到的第一行数据填充给对象 jason

    查询参数绑定
    rows, err = db.NamedQuery(`SELECT * FROM person WHERE first_name=:first_name`, jason)
    NamedQuery 会从对象 jason 字段去查找 sql 语句中:参数

    python 中用 sqlalchemy 怎么实现?? 或者其它 python 库可以实现也行
    Supplement 1  ·  Apr 14, 2019
    暂时放弃原生 sql

    目前是这样实现的:

    inserter = expression.insert(model.User).values(name=name, phone=phone, account_id=account_id)
    res = session.execute(inserter)


    user = session.query(model.User).filter(model.User.id==account_id).first()

    期待 python 专家提供能支持原生 sql 的方案
    2 replies  •  2019-04-13 18:10:31 +08:00
    neoblackcap
        1
    neoblackcap  
       Apr 13, 2019 via iPhone
    可以的,你写 model 的时候指定字段名就可以了
    fngtz
        2
    fngtz  
       Apr 13, 2019 via iPhone
    PEP 249
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2245 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 04:55 · PVG 12:55 · LAX 21:55 · JFK 00:55
    ♥ Do have faith in what you're doing.