簡體   English   中英

python-嘗試將數據上傳到mysql,但寫入txt除外

[英]python- try data upload to mysql except write txt

我編寫了一個循環,將一些數據上傳到MySQL數據庫。 當wifi無法正常工作時,應該將數據寫入txt文件中。 問題是它不寫txt文件。 我已經初始化了數據庫(稱為“數據庫”)和游標(稱為“光標”)。 該txt文件稱為“測試”。

編輯:通過嘗試插入和拔出以太網電纜,我意識到當我重新插入電纜時,會自動以相同的時間戳發送一堆數據(可能保存在ram或某些緩存中-每當我重新啟動程序時也會發生這種情況但規模較小)。 您是否認為還有另一種備份方法? 也許是通過在txt文件上寫入所有內容並在每1GB數據刪除后刪除txt文件(這樣SD才能裝滿-它在Raspberry Pi 2上)?

try:
  try:
    cursor.execute("""INSERT INTO table (collumn1) VALUES(%s)""", (temperature))
    database.commit
  except:
    text=open("test.txt","a")
    test.write(temperature + "\n")
    test.close()
except:
  print "FAIL"

由於write()函數需要一個字符緩沖區對象,因此在將溫度作為參數傳遞給write函數時,您可能需要將溫度轉換為字符串。

test.write(str(temperature) + "\n")

這是我的方法:

import urllib, time, mysqldb


time.sleep(1) # Protects Overlap from execfile
url = "https://www.google.co.uk/"


try:
   checkcon = urllib.urlopen(url)
except Exception as e:
    """
    If the program gets a socket error
    it goes to sleep, after that it restarts
    and closes this Script
    """
    time.sleep(5)# retry timer
    execfile('/path/to/your/file.py')
    raise IOError(e)


# Now that you know connection is working
try:
    cursor.execute("""INSERT INTO table (collumn1) VALUES(%s)""", (temperature))
    database.commit()
except MySQLdb.IntegrityError as e:
    # Database Error
    with open ('test.txt'), 'a' as f:
        f.write(temperature)
        f.close()
    raise IOError(e)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM