简体   繁体   English

MySQL / Python连接InterfaceError到数据库

[英]MySQL/Python Connection InterfaceError to Database

I do not understand why I get the following connection error. 我不明白为什么我得到以下连接错误。 I have tried many different iterations of placement of the cur = db.cursor() and cur.close(),db.close(). 我尝试了很多不同的cur = db.cursor()和cur.close(),db.close()的放置迭代。

The loop runs fine for one cycle (and writes to the database successfully). 循环运行良好一个周期(并成功写入数据库)。 However, in the second cycle of the loop it gives me the error below. 但是,在循环的第二个循环中,它给出了下面的错误。 What is wrong with my code? 我的代码出了什么问题?

#!/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)

Error message: 错误信息:

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, '')

Don't close your connection each time through the loop. 每次循环时都不要关闭连接。
Close it after the loop is finished. 循环结束后关闭它。

Move: 移动:

db.close()

To the line after your while True: is finished executing. 在你的while True:之后的行while True:完成执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM