动态SQL拼接
问题
在python利用pymysql执行sql语句时,由于没用的orm模型,只能手写sql,这么做的不方便之处:
- 参数个数变化时,sql语句就要有很大的调整,很不方便。
- 在爬虫中,我们插入的往往是一个对象,把对象解析出来再拼接sql语句很麻烦。
今天我们来学习一种动态sql的写法,也可以说是通用型sql的写法,当然这个写法是我在看崔庆才大神的博客中学到的,参考链接:
https://cuiqingcai.com/5578.html
特别感谢!
insert
在执行插入语句时,我们可以动态解析要插入的对象,解析出来的字段名、字段数和字段值之后就可以动态构造一个sql。
def execute_insert(self,table,item):
keys = ', '.join(item.keys())
values = ', '.join(['%s'] * len(item))
sql = 'INSERT INTO {table}({keys}) VALUES ({values})'.format(table=table, keys=keys, values=values)
while 1:
try:
self.cur.execute(sql, tuple(item.values()))
self.conn.commit()
break
except Exception as e:
print("execute insert error,retry after 5s...")
print(e)
time.sleep(5)
self.get_mysql_conn()
update
def execute_update(self,table,item):
keys = ', '.join(item.keys())
values = ', '.join(['%s'] * len(item))
sql = 'INSERT INTO {table}({keys}) VALUES ({values}) ON DUPLICATE KEY UPDATE'.format(table=table, keys=keys,
values=values)
update = ','.join([" {key} = %s".format(key=key) for key in item])
sql += update
while 1:
try:
self.cur.execute(sql, tuple(item.values()) * 2)
self.conn.commit()
break
except Exception as e:
print("execute update error,retry after 5s...")
print(e)
time.sleep(5)
self.get_mysql_conn()
其中,ON DUPLICATE KEY UPDATE 的作用是主键不存在则插入,主键存在则更新
查询数据库表所有字段,将查出的记录生成字典,key为字段名
sql = "select * from {0} where basic_info is not NULL".format(table)
cur.execute(sql)
results = cur.fetchall()
column_names = []
desc = cur.description
for field in desc:
column_names.append(field[0])
for result in results:
weibo_user = {}
for i,value in enumerate(result):
weibo_user[column_names[i]] = value
print(weibo_user)
动态选择调用哪个方法
import operator
action = {
"+": operator.add,
"-": operator.sub,
"/": operator.truediv,
"*": operator.mul,
"**": pow
}
print(action['-'](50, 25)) # 25