python - 增加特定行的列中的整数值

标签 python mysql python-3.x

我有一个表,其中包含 URL 列表以及它们被访问的次数。使用 python,如何创建一个 SQL 查询来增加特定 URL 的 HITS 列?即特定行?

到目前为止我已经:

def insertURL(url) :
    ##query to fetch all URLs
    sql = "SELECT URL_visited FROM URL"

    ##query to insert a number into the HITS column
    insert_sql = "INSERT INTO URL_visited (total_hits)"
    insert_sql = insert_sql + "VALUES('"+1+"')"

    ##execute sql query to fetch URLs 
    cursor.execute(sql)
    results = cursor.fetchall()

    ##flag to check whether the URL already exists in table
    flag = 0 

    ##checking if URL exists
    for row in results:
        if (row==url) :
            flag = 1 

    ##if yes, increment HITS column for that URL (specific row)
    if flag == 1 :
        ##how to do?? 

如您所见,我可以在 HITS 列中插入一个数字,但如何增加特定行的值?

最佳答案

优化方法:只需更新/增量特定url_visited值的total_hits列值:

(考虑urls是目标表名称)

def update_url_hits(url):
   sql_query = "UPDATE urls SET total_hits = total_hits + 1 WHERE url_visited = %"
   cursor.execute(sql_query, (url,))
   connection.commit()

关于python - 增加特定行的列中的整数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57430164/

相关文章:

python - 套接字断开连接时退出 Python While 循环

python - 如何避免在内部 Python 样式循环中调用相同的函数

python - 如何在while循环中只执行一次for循环中的if else语句

python - 用于计算列表中元素出现次数的递归 Python 函数

python - Python string.find 使用什么?

Python:如何在分配过程中保持可变内存位置?

python - 将行插入到 Pandas DataFrame 中,同时保持列数据类型

sql - 使用 SQL,如何计算具有特定值的行的百分比?

mysql - 选择 bool 值但反转值

mysql - MySQL 如何决定在 group by 子句中返回哪个 id?