在指定的列中递增整数值

2024-04-25 23:17:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含URL列表和访问次数的表。使用python,如何创建一个SQL查询来增加特定URL的HITS列?i、 e.具体的一行

到目前为止,我已经:

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列中插入一个数字,但如何在特定行中增加值


Tags: thetourlsqlifcolumnfetchquery
1条回答
网友
1楼 · 发布于 2024-04-25 23:17:40

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

(考虑到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()

相关问题 更多 >