在特定行的列中递增整数值

时间:2019-08-09 12:32:51

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

1 个答案:

答案 0 :(得分:0)

优化的方法:仅针对特定total_hits值的更新/增量 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()