2017-03-16 49 views
1

總之,我有一個腳本,需要我們的零售UPC比較價格。Python MySQL增量但不能插入

該查詢不插入數據,但它確實增加了ID號(在操作中......沒有數據)。當我粘貼查詢並複製並粘貼到MySQL時,它會成功粘貼。

操作步驟:

抓鬥UPC從upc.txt

在網站上比較

獲取價格和網站(網站包含的推薦鏈接(等待實際的鏈接)

發送到數據庫

沒有錯誤顯示 - 只是它成功插入。沒有實際的數據被插入 - 唯一的事wa被改變的是操作中的自動增量ID。

附註,這完全是一個草案。我意識到SQL注入是開放的。

import urllib 
import re 
import MySQLdb 
import requests 

upcfile = open("upc.txt") 

upcslist = upcfile.read() 


newupclist = upcslist.split("\n") 

conn = MySQLdb.connect(host="127.0.0.1",user="root",passwd="",db="Items") 
i=0 
while i < len(upcslist): 
    url = "https://www.(REMOVED).com/search"+newupclist[i]+"?view=list" 
    htmlfile = urllib.urlopen(url) 
    htmltext = htmlfile.read() 
    regex = '<td class="price-column">(.+?)</td>' 
    pattern = re.compile(regex) 
    price = re.findall(pattern,htmltext) 
    itemLinkRegex = '<td class="link-column"><a href="(.+?)" target="_blank">' 
    itemLinkPattern = re.compile(itemLinkRegex) 
    itemLink = re.findall(itemLinkPattern,htmltext) 
    p=0 
    try: 
     while p <len(price): 
      try: 
       r = requests.get(itemLink[p], allow_redirects=False) 
       itemLinkFormat = r.headers['Location'] 
      except: 
       itemLinkFormat = itemLink[p] 
       pass 
      #print "Sent to Database Competitor Price: UPC ["+newupclist[i]+"] - Price: ", price[p]+" Item URL: ", itemLinkFormat 
      pre = ''.join(price[p].split('$', 1)) 
      priceformat = ''.join(pre.split(',', 1)) 
      skuNumber = newupclist[i] 
      try: 
       query = "INSERT INTO Entry (SKU, Price, Item_link) VALUES (" 
       query = query+"'"+skuNumber+"','"+priceformat+"','"+itemLinkFormat+"')" 
       print query 
       x = conn.cursor() 
       x.execute(query) 
       row = x.fetchall() 
      except: 
       print "Error, Not a valid number to enter into database." 
       pass 
       p+=1 
      p+=1 
     i+=1 
    except: 
     pass 
     i+=1 

回答

1

不明白爲什麼這樣做fetchAll,嘗試con.commit()然後cur.rowcount檢查受影響的行。

而且,你釣到的魚也能像這樣

except cur.Error, e: 

    if con: 
     con.rollback() 

    print "Error %d: %s" % (e.args[0],e.args[1]) 
    sys.exit(1) 
+0

感謝隊友..完美工作:) – hinteractive02

+0

@ hinteractive02高興它確實:) – Alfabravo