One - One Code All

Blog Content

python任意字典生成sql,insert,update

Python MySQL   2014-04-27 14:55:48

python 任意字典生成sql: insert。

tb = 'student'
dt = {'name': 'ArYe', 'age': 15, 'height': None}
ls = [(k, v) for k, v in dt.items() if v is not None]
sentence = 'INSERT %s (' % tb + ','.join([i[0] for i in ls]) +\
           ') VALUES (' + ','.join(repr(i[1]) for i in ls) + ');'
print(sentence)


python 任意字典生成sql : update。

table_name = 'student'
d = {'name': 'ArYe', 'age': 15}   # 更新的字段及对应值
t = ('id', 307)  # 更新所需条件
# 自动构造update语句
sentence = 'UPDATE %s SET ' % table_name + ','.join(['%s=%r' % (k, d[k]) for k in d]) + ' WHERE %s=%r;' % (t[0], t[1])
# 打印
print(sentence)


组合类。

import pymysql

class Mysql:
    def __init__(self, db_name, tb_name):
        self.db = pymysql.connect('localhost', 'root', 'yellow', charset='utf8', db=db_name)
        self.cursor = self.db.cursor()
        self.tb = tb_name

    def __del__(self):
        self.cursor.close()
        self.db.close()

    def insert(self, dt):
        ls = [(k, dt[k]) for k in dt if dt[k] is not None]
        sql = 'insert %s (' % self.tb + ','.join(i[0] for i in ls) +\
              ') values (' + ','.join('%r' % i[1] for i in ls) + ');'
        self.cursor.execute(sql)
        self.db.commit()


    def commit(self, sql):
        try:
            self.cursor.execute(sql)
            self.db.commit()
        except Exception as error:
            print('\033[031m', error, '\033[0m', sep='')

    def update(self, dt_update, dt_condition, table):
        sql = 'UPDATE %s SET ' % table + ','.join('%s=%r' % (k, dt_update[k]) for k in dt_update)\
              + ' WHERE ' + ' AND '.join('%s=%r' % (k, dt_condition[k]) for k in dt_condition) + ';'
        self.commit(sql)



上一篇:python中pandas读取处理excel
下一篇:airflow删除某个dag

The minute you think of giving up, think of the reason why you held on so long.