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

291 天前
 craftx

抄下 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: "asavea@ab.co.nz"}

	// 插入到数据库
    // sqlx 将 sql 语言中的“:field”替换为对象字段的值
    _, err = db.NamedExec(`INSERT INTO person (first_name, last_name, email)
        VALUES (:first_name, :last_name, :email)`, personStructs)

992 次点击
所在节点    Python
6 条回复
NoOneNoBody
291 天前
dataclass + f-format/string.Template ?
sql 执行需要另外实现
Vegetable
291 天前
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
290 天前
随便上个 ORM 都比这个强吧?轻量的 peewee ,或者直接 sqlalchemy
craftx
290 天前
@NoOneNoBody 直接格式化 sql ,不太好吧?
craftx
290 天前
@knightdf peewee sqlalchemy 都是侵入式的吧?
NoOneNoBody
290 天前
@craftx #4
生成一个 sql 语句而已
值是执行时另外传的

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/959042

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX