MySQL用字典插入,生成SQL语句。

def make_sql(table_name='user_info', *, user_info=None):
    fields = ','.join(user_info.keys()).rstrip(',')
    sql = "insert into `%s` (%s) values (%s)" % (table_name, fields, ('{!r},' * len(user_info)).rstrip(','))
    field_values = list(user_info.values())
    sql = sql.format(*field_values)
    return sql
make_sql(user_info={'name': 'sidian', 'age': 18})
输出
insert into `user_info` (name,age) values ('sidian',18)

要求字典的key与SQL的插入字段KEY的子集,如果有需要可以加一个前置判断,剔除不在SQL字段里面的KEY。

 

 

对入插入的值部分,pymysql原生是支持dict的

If args is a list or tuple, %s can be used as a placeholder in the query.
If args is a dict, %(name)s can be used as a placeholder in the query.

"INSERT INTO `symbol_cusip` (CUSIP, Symbol, Description) " \
"VALUES (%(CUSIP)s, %(Symbol)s, %(Description)s)"
插入的数据
 {'CUSIP': '531229722', 'Symbol': 'LLYVK', 'Description': 'Liberty Media Liberty Live Series C'}


posted @ 2020-12-18 14:19  就是想学习  阅读(466)  评论(0编辑  收藏  举报