V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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
craftx
V2EX  ›  Python

Python 如何实现类似 go 语言 sqlx 的 NamedXXX 操作?

  •  
  •   craftx · 279 天前 · 976 次点击
    这是一个创建于 279 天前的主题,其中的信息可能已经有所发展或是发生改变。

    抄下 sqlx 文档的代码

    	
        // 定义结构体
        type Person struct {
            FirstName string `db:"first_name"`
            LastName  string `db:"last_name"`
            Email     string `db:"email"`
        }
    
        // 创建对象 
        personStructs := Person{FirstName: "Ardie", LastName: "Savea", Email: "[email protected]"}
    
    	// 插入到数据库
        // sqlx 将 sql 语言中的“:field”替换为对象字段的值
        _, err = db.NamedExec(`INSERT INTO person (first_name, last_name, email)
            VALUES (:first_name, :last_name, :email)`, personStructs)
    
    
    6 条回复    2023-07-24 21:13:56 +08:00
    NoOneNoBody
        1
    NoOneNoBody  
       279 天前
    dataclass + f-format/string.Template ?
    sql 执行需要另外实现
    Vegetable
        2
    Vegetable  
       279 天前
    https://pymysql.readthedocs.io/en/latest/modules/cursors.html#pymysql.cursors.Cursor.execute

    execute("INSERT INTO person (first_name, last_name, email)
    VALUES (%(first_name)s, %(last_name)s, %(email)s)", args=dict(first_name="",last_name="",email=""))
    只需要解决 class to dict 就行了,方案多的是

    有点原始了,这不就是 ORM 吗?这种不上不下的操作是什么特殊的需求
    knightdf
        3
    knightdf  
       278 天前   ❤️ 1
    随便上个 ORM 都比这个强吧?轻量的 peewee ,或者直接 sqlalchemy
    craftx
        4
    craftx  
    OP
       278 天前
    @NoOneNoBody 直接格式化 sql ,不太好吧?
    craftx
        5
    craftx  
    OP
       278 天前
    @knightdf peewee sqlalchemy 都是侵入式的吧?
    NoOneNoBody
        6
    NoOneNoBody  
       278 天前
    @craftx #4
    生成一个 sql 语句而已
    值是执行时另外传的
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   900 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 20:08 · PVG 04:08 · LAX 13:08 · JFK 16:08
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.