python根据字典生成万能SQL语句(INSERT)

def connect_mysql(item, table_name):
	'''
	item: 传入的字典,key的值必须与数据库的字段对应
	'''
    conn = pymysql.connect(host='localhost', port=3306, database='news', user='root', password='password',
                           charset='utf8')
    # 获得Cursor对象
    cursor = conn.cursor()
    ls = [(k, v) for k, v in item.items() if v is not None]
    print(' %s (' % table_name + ','.join([i[0] for i in ls]) + ')')
    sql = 'INSERT INTO %s (' % table_name + ','.join([i[0] for i in ls]) + ') VALUES (' + ','.join(
        repr(i[1]) for i in ls) + ');'

    print(sql)

猜你喜欢

转载自blog.csdn.net/qq_43035475/article/details/106189273
今日推荐