使用selenium做ui自動化時,產生的數據往往涉及多張表,需要執行多條sql語句進行刪除
下面是使用for循環來執行sql,執行速度非常快:
幾個記住點:
1、將sql全部寫入一個字符串中,使用split方法進行拆分
2、使用for循環執行sql,執行完記得要commit提交事務
delete_sql = "DELETE FROM 表A WHERE id = @userid;
DELETE FROM 表B WHERE id = @userid"
class DB:
def __init__(self):
# 連接數據庫
self.conn = pymysql.connect(
host=Setting.sql_msg['host'],
port=3306,
user=Setting.sql_msg['user'],
password=Setting.sql_msg['password'],
cursorclass=pymysql.cursors.DictCursor,
charset="utf8")
# 創建游標
self.cur = self.conn.cursor()
def delete_sql(self,userid):
"""刪除測試數據"""
# 刪除數據的sql
re_sql = delete_sql.replace('@userid', str(userid))
sql_list = re_sql.split(';')
# 循環執行多條sql語句
for sql in sql_list:
self.cur.execute(sql)
# 記得一定要提交事務
self.conn.commit()
self.cur.close()
self.conn.close()
