python pymysql动态绑定变量值到数据库字段

kxkpmulp  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(525)

我尝试动态绑定要插入到数据库表列中的变量值。
json中的变量值示例:

document= {'zipCode': '99999', 
           'name': 'tester', 
           'company': 'xxxx'}

我的数据库表列为:
表名:table1
列:id、邮政编码、姓名、公司
我的python代码:

with connection.cursor() as cursor:
     sql = "INSERT INTO table1(zip_code, name, company) VALUES (%s,%s,%s)"
            cursor.execute(sql,(document['zipCode'],
                                document['name'],
                                document['company']))
connection.commit()

但是,如果文档中缺少一个键值,insert查询肯定会出错。i、 e.文档变量中只存在文档['name']
有没有想过处理这个问题以获得高效的代码?

nhaq1z21

nhaq1z211#

一般来说,这就是 SQLAlchemy 或者 Peewee 对你来说很容易解决。
但是,如果我要实现的话,我可能会根据可用的键做一些“动态”的事情:

QUERY = "INSERT INTO table1({columns}) VALUES ({values})"

def get_query(document):
   columns = list(document.keys())

   return QUERY.format(columns=", ".join(columns),
                       values=", ".join('%({})s'.format(column) for column in columns))

示例用法:

In [12]: get_query({'zipCode': '99999', 'name': 'tester', 'company': 'xxxx'})
Out[12]: 'INSERT INTO table1(company, zipCode, name) VALUES (%(company)s, %(zipCode)s, %(name)s)'

In [13]: get_query({'name': 'tester'})
Out[13]: 'INSERT INTO table1(name) VALUES (%(name)s)'

然后,只需使用 document 字典,因为我们在查询中创建了命名占位符:

cursor.execute(get_query(document), document)

相关问题