使用fetchone()只将第一行输入mysql,然后关闭

0qx6xfy6  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(275)

我的代码以退出代码0结束,但只更新第一行,我在尝试更新它时出错,但无法找到它。我是个新手。

import pymysql
from bs4 import BeautifulSoup
from selenium import webdriver

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--incognito")
driver = webdriver.Chrome(chrome_options=chrome_options)

mainDB_cnx = pymysql.connect(user='', password='',
                             host='',
                             database='Content', use_unicode=True, charset="utf8mb4")
mainDB_cursor = mainDB_cnx.cursor()

mainDB_cursor.execute("SELECT content_url FROM Content.Reddit")
row = mainDB_cursor.fetchone()
while row is not None:
    print(row[0])
    open_page = driver.get(row[0])
    html_source = driver.page_source
    soup = BeautifulSoup(html_source, 'html.parser')
    for script in soup(["script", "style"]):
        script.decompose()
    content_names = soup.get_text()
    with mainDB_cnx:
        mainDB_cursor.execute("""
            UPDATE Content.Reddit
            SET artists_names_2 = %s
            WHERE artists_url = %s""", (content_names.encode('utf-8'),row[0]))
    row = mainDB_cursor.fetchone()

# Commit the transaction

mainDB_cnx.commit()

# Close the cursor

mainDB_cursor.close()

# Close the database connection

mainDB_cnx.close()
rslzwgfq

rslzwgfq1#

当您仍然需要第一个结果集时,您正在重用同一个游标来执行更多sql:

with mainDB_cnx:
    mainDB_cursor.execute("""
        UPDATE Content.Reddit
        SET artists_names_2 = %s
        WHERE artists_url = %s""", (content_names.encode('utf-8'),row[0]))

这将替换 SELECT -是的,尽管这是一个 UPDATE .

相关问题