2016-12-06 31 views
0

我的劇本通常正確插入數據到MySQL數據庫,但是,當我將其安排爲每10秒運行(此調度調用該腳本每10秒),它約50%的時間崩潰。警告:根:無法插入值 - 插入並不總是成功到mysql

有什麼建議嗎?

some unimportant code here 

# Calculate pulse length 
elapsed = stop-start 

# Distance pulse travelled in that time is time 
# multiplied by the speed of sound (cm/s) 
distance = elapsed * speedSound 

# That was the distance there and back so halve the value 
distance = distance/2 
distance = '{:f}'.format(distance) 

    print(distance) 

time = time.strftime('%Y-%m-%d %H:%M:%S') 
print(time) 
# Open database connection 
db = MySQLdb.connect("192.168.2.3","sonic","123456","Pi") 


cursor = db.cursor() 


sql = "INSERT INTO UltraSonic (distance, time) VALUES (%s, %s)" 

try: 

    cursor.execute(sql, (distance, time)) 

    db.commit() 

# Rollback in case there is any error 
# db.rollback() 
except MySQLdb.IntegrityError: 
    logging.warn("failed to insert values %s, %s", distance, time) 
# disconnect from server 
finally: 
    db.close() 
print ("Ok") 
+1

請附上您遇到任何錯誤。您可能要刪除你的「除了MySQLdb.IntegrityError」這樣你就可以在真正的例外獲得,而不是僅僅記錄警告被拋出。 – joeb

+0

如果這是正確的輸出,我只是從代碼中刪除了異常:Traceback(最近調用最後一個): 文件「sonic.py」,第80行,在 cursor.execute(sql,(distance,time )) 文件「/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py」,第174行,執行 self.errorhandler(self,exc,value) 文件「/ usr/lib/python2 「.7/dist-packages/MySQLdb/connections.py」,第36行,在defaulterrorhandler中 raise errorclass,errorvalue _mysql_exceptions.IntegrityError:(1062,「'PRIMARY'鍵'重複條目'17 .384983'」) –

+0

您正在嘗試插入違反表格規則的行。您必須調整您的表格或您的代碼以確保不會發生。 – joeb

回答

0

的問題是在數據庫表中,主要設置爲PRI,什麼也不允許重複的條目,這是我需要的。

移除PRI解決的問題。感謝joeb!