2016-12-04 168 views
1

我不明白爲什麼我得到以下連接錯誤。我已經嘗試了許多不同的迭代來放置cur = db.cursor()和cur.close(),db.close()。MySQL/Python連接InterfaceError到數據庫

循環正常運行一個週期(併成功寫入數據庫)。但是,在循環的第二個循環中,它給了我下面的錯誤。我的代碼有什麼問題?

#!/usr/bin/env python 
import RPi.GPIO as GPIO 
import time 
import datetime 
import PCF8591 as ADC 
import math 
import Adafruit_DHT as DHT 
import Adafruit_DHT 
from time import strftime 
DHT_TYPE = Adafruit_DHT.DHT11 
#setup to write to MySQL database 
import MySQLdb 

#define how long to wait between readings 
FREQUENCY_SECONDS  = 2 

DO = 17 
GPIO.setmode(GPIO.BCM) 

#Variables for MySQL 
db = MySQLdb.Connection(host= "localhost", 
       user="mysql-user", 
       passwd="password", 
       db="database") 

#humiture variables 
Sensor = 11 
humiture = 17 

print('Press Ctrl-C to quit.') 

def setup(): 
    print 'Setting up, please wait...' 
    ADC.setup(0x48) 
    GPIO.setup(DO, GPIO.IN) 

def destroy(): 
    GPIO.cleanup() 

while True: 
    humidity, temperature = DHT.read_retry(Sensor, humiture) 
    tempF = (temperature*1.8)+32 
    datetimeWrite = (time.strftime("%Y-%m-%d ") + time.strftime("%H:%M:%S")) 
    print datetimeWrite 
    print('Temperature: {0:0.1f} F'.format(tempF)) 
    print('Humidity: {0:0.1f} %'.format(humidity)) 
    #connect to wordpress database: 
    cur = db.cursor() 
    sql = ("""INSERT INTO humiture (dateTime,temp, humidity) VALUES (%s,%s,%s)""",(datetimeWrite,tempF,humidity)) 
    try: 
     print "Writing to database..." 

     # Execute the SQL command 
     cur.execute(*sql) 
     # Commit your changes in the database 
     db.commit() 

     print "Write Complete" 

    except KeyboardInterrupt: 
     destroy() 
     break 

    cur.close() 
    db.close() 
    # Wait before taking another reading 
    time.sleep(FREQUENCY_SECONDS) 

錯誤消息:

Traceback (most recent call last): 
    File "Sensor_MySQLv2.py", line 54, in <module> 
    cur.execute(*sql) 
    File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 155, in execute 
    charset = db.character_set_name() 
_mysql_exceptions.InterfaceError: (0, '') 

回答

0

不要通過循環每次關閉連接。
循環結束後關閉它。

移動:

db.close() 

行之後你while True:執行完畢。

+0

這樣做。我將db.close移入了except部分,現在它循環並寫入數據庫,沒有任何問題。謝謝! – RPiNoob