建议先看Python列表生成式和字典生成式,再来看这篇。
In [1]: import MySQLdb as mysql
In [2]: conn=mysql.connect(user='root',host='127.0.0.1',passwd='123456',db='lyz',charset='utf8')
In [3]: conn.autocommit(True)
In [4]: cur = conn.cursor()
In [5]: info = ['id','name','name_cn','email','mobile']
In [6]: sql = 'select %s from users'%','.join(info)
In [7]: sql
Out[7]: 'select id,name,name_cn,email,mobile from users'
In [8]: cur.execute(sql)
Out[8]: 2L
In [9]: res = cur.fetchall() # fetchall()获得的是个嵌套的元组
In [10]: res
Out[10]:
((1L,
u'liuyongzhan',
u'\u5218\u6c38\u6808',
u'[email protected]',
u'2147483647'),
(6L, u'lyz', u'1111', u'1111', u'1111'))
高级用法:把嵌套元组变成一个列表,列表里嵌套字典
In [11]: ha = [dict((k,row[i]) for i,k in enumerate(info)) for row in res]
In [12]: ha
Out[12]:
[{'email': u'[email protected]',
'id': 1L,
'mobile': u'2147483647',
'name': u'liuyongzhan',
'name_cn': u'\u5218\u6c38\u6808'},
{'email': u'1111',
'id': 6L,
'mobile': u'1111',
'name': u'lyz',
'name_cn': u'1111'}]
一般写法:
hostname = request.form.get('hostname')
cpu = request.form.get('cpu')
mem = request.form.get('mem')
exdate = request.form.get('exdate')
author = request.form.get('author')
note = request.form.get('note')
sql='insert into zichan (hostname,cpu,mem,exdate,author,note) values ("%s","%s","%s","%s","%s","%s")' %(hostname,cpu,mem,exdate,author,note)
高大上写法:
data = dict(request.form) # 或者前端直接以json格式传过来,就可以写成data=request.get_json()
ZiChan = ['hostname','cpu','mem','exdate','author','note']
sql='insert into zichan (%s) values (%s)'%(','.join(ZiChan),','.join(['"%s"'%data[x][0] for x in ZiChan]))
也可以这样:
data = {'name':'lyz','age':26,'mobile':15768216871,'email':'[email protected]'}
key,values = [],[]
for k,v in data.items():
key.append(k)
values.append('"%s"'%v)
sql = 'insert into users (%s) values (%s)'%(','.join(key),','.join(values))
执行结果:
'insert into users (mobile,age,name,email) values ("15768216871","26","lyz","[email protected]")'
一般写法:
ida = request.form.get('id')
hostname = request.form.get('hostname')
cpu = request.form.get('cpu')
mem = request.form.get('mem')
exdate = request.form.get('exdate')
author = request.form.get('author')
note = request.form.get('note')
sql = 'update zichan set hostname ="%s",cpu ="%s",mem ="%s",exdate ="%s",author ="%s",note ="%s" where id=%s'%(hostname,cpu,mem,exdate,author,note,ida)
高大上写法:
方法1:
data = dict(request.form)
ida = data.get('id',None)[0]
ZiChan = ['hostname','cpu','mem','exdate','author','note']
arr = ["%s='%s'" %(k,data[k][0]) for k in ZiChan]
sql = 'update zichan set %s where id=%s'%(','.join(arr),ida)
方法2:方法2这种写法是最优的,那么前端传什么字段过来,就更新对应字段。字段就不会写死了。
方法1主要是前端jquery传过来的数据没优化好,如果前端以json格式传过来,而且里边包含一个id的key和一个data的key,id就只对应一个id,而data的value是一个字典,字典里用每个资产信息字段作为key,就可以用以下方法:
data = request.get_json()
ida = data.get('id',None)
data = data.get('data',None)
arr = ["%s='%s'"%(k,data[k] for k in data)] # 结果为:["’hostname‘=’xxx‘","’cpu‘=’xxx‘",......]
sql = 'update zichan set %s where id=%s'%(','.join(arr),ida)