python mysql 字段与关键字冲突解决

来源:互联网 发布:泰国蛇毒洗面奶知乎 编辑:程序博客网 时间:2024/06/05 23:45

解决方法:python中把字段名称用反引号(`),也就是ESC下面~那个按钮。

示例:

数据字段设计如下截图所示

待插入数据:

datas = {    'sign_event':[        {'id': 1, 'name': '华为mate9发布会' , 'limit': 100, 'status': 1, 'address': '会展中心1号厅', 'start_time': '2017-09-20 14:00:00','create_time':'2017-08-20 14:00:00'},        {'id': 2, 'name': '华为P1000发布会' , 'limit': 200, 'status': 1, 'address': '会展中心2号厅', 'start_time': '2017-09-20 14:00:00','create_time':'2017-08-20 14:00:00'},        {'id': 3, 'name': 'IPHONE888发布会' , 'limit': 300, 'status': 1, 'address': '会展中心3号厅', 'start_time': '2017-09-20 14:00:00','create_time':'2017-08-20 14:00:00'},        {'id': 4, 'name': '半壁江山66演唱会' , 'limit': 400, 'status': 1, 'address': '会展中心4号厅', 'start_time': '2017-09-20 14:00:00','create_time':'2017-08-20 14:00:00'},        {'id': 5, 'name': '金融P222222P上线' , 'limit': 500, 'status': 1, 'address': '会展中心5号厅', 'start_time': '2017-09-20 14:00:00','create_time':'2017-08-20 14:00:00'},        {'id': 6, 'name': '未命名0000发布会' , 'limit': 600, 'status': 1, 'address': '会展中心6号厅', 'start_time': '2017-09-20 14:00:00','create_time':'2017-08-20 14:00:00'},    ],}
插入语句实现:

1.获取某个表的所有待插入数据

 for tablename,data in datas.items():         for d in data:             self.insert_datatable(tablename,d) self.close_dataConnetion()


2.每个表的数据,逐条循环插入到该表中


 def insert_datatable(self, tablename, table_data):        keys = {}        for key in  table_data:            # 从数据字段中取出列名,列名用反单引号括起来;--解决列名与mysql关键字冲突            keys[key] = "`"+str(key)+"`"            table_data[key] = "'"+str(table_data[key])+"'"        key = ','.join(keys.values())        value = ','.join(table_data.values())        sql = "INSERT INTO " + tablename + " ( " + key + " ) VALUES ( " + value +" );"        with self.connection.cursor() as cursor:            cursor.execute('SET FOREIGN_KEY_CHECKS=0;') #取消外键约束            cursor.execute(sql)        self.connection.commit()


原创粉丝点击