推荐学习书目
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 · Jul 23, 2023 · 1529 views
    This topic created in 1039 days ago, the information mentioned may be changed or developed.

    抄下 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 replies    2023-07-24 21:13:56 +08:00
    NoOneNoBody
        1
    NoOneNoBody  
       Jul 23, 2023
    dataclass + f-format/string.Template ?
    sql 执行需要另外实现
    Vegetable
        2
    Vegetable  
       Jul 23, 2023
    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  
       Jul 24, 2023   ❤️ 1
    随便上个 ORM 都比这个强吧?轻量的 peewee ,或者直接 sqlalchemy
    craftx
        4
    craftx  
    OP
       Jul 24, 2023
    @NoOneNoBody 直接格式化 sql ,不太好吧?
    craftx
        5
    craftx  
    OP
       Jul 24, 2023
    @knightdf peewee sqlalchemy 都是侵入式的吧?
    NoOneNoBody
        6
    NoOneNoBody  
       Jul 24, 2023
    @craftx #4
    生成一个 sql 语句而已
    值是执行时另外传的
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4386 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 00:11 · PVG 08:11 · LAX 17:11 · JFK 20:11
    ♥ Do have faith in what you're doing.