解决方法:python中把字段名称用反引号(`),也就是ESC下面~那个按钮。
示例:
数据字段设计如下截图所示
待插入数据:
1
2
3
4
5
6
7
8
9
10
|
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.获取某个表的所有待插入数据
1
2
3
4
|
for tablename,data in datas.items(): for d in data: self.insert_datatable(tablename,d) self.close_dataConnetion() |
2.每个表的数据,逐条循环插入到该表中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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 () |
补充拓展:python 数据库 % 冲突问题解决
在使用python后台调用 MySQL数据库的时候会有 「%」的关键字冲突问题,比如 用Python后端读取 MySQL 中记录的逻辑,在 impala端执行,其中涉及到模糊匹配的 「%」会报错
解决:SQL逻辑中的单个「%」换为「%%」即可,不错的 trip。