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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM