pymysql批量增删改查

# coding=utf-8

import time
import pymysql.cursors

conn = pymysql.connect(host='rm-xxx.mysql.rds.aliyuncs.com',
                       port=3306,
                       user='dba',
                       password='xxxxx',
                       db='app',
                       charset='utf8')
cursor = conn.cursor()
# conn.ping(reconnect=True)

count = 0
posts =[]
for post in posts:
    try:
        sql = 'DELETE FROM user_like WHERE user_id=%s and like_post_id=%s'
        ret = cursor.executemany(sql, ((1,2), (3,4), (5,6)))
        conn.commit()
    except Exception as e:
        print("batch Exception:", e)

    count +=1

cursor.close()
conn.close()


# 基本sql语句写法
# INSERT INTO star(name,gender) VALUES(“XX”, 20)
# SELECT * FROM app.user_post WHERE post_id LIKE '%xxxx%';
# UPDATE app.user_post SET post_id=replace(post_id,'\'','’);
# UPDATE app.user_post SET  province = ‘xxx', city =‘xxx';
# DELETE FROM app.user_post where updated_at = '0000-00-00 00:00:00’;


# 带参数构造语句的基本写法
# sql = 'select user_id, post_id from user_post where user_id="{user_id}" and post_id="{post_id}"'.format(user_id=user_id, post_id=post_id)
# sql = 'SELECT count(*) FROM user_like where like_post_id = "%s"' % ("xxx")
# sql = 'update star set gender="{gender}", height="{height}" where star_id="{star_id}"'.format(gender='M', height=180, star_id=123456789)

  

注意插入数字也是%s

posted @ 2019-03-07 21:09  Adamanter  阅读(3593)  评论(0编辑  收藏  举报