【问题标题】:MySQL/Python Connection InterfaceError to DatabaseMySQL/Python 连接接口错误到数据库
【发布时间】:2017-04-19 02:29:46
【问题描述】:

我不明白为什么会出现以下连接错误。我尝试了许多不同的 cur = db.cursor() 和 cur.close(),db.close() 放置迭代。

循环运行良好一个周期(并成功写入数据库)。但是,在循环的第二个循环中,它给了我下面的错误。我的代码有什么问题?

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

【问题讨论】:

    标签: python mysql error-handling connection


    【解决方案1】:

    不要每次都通过循环关闭连接。
    循环结束后关闭。

    移动:

    db.close()
    

    while True: 执行完毕后的行。

    【讨论】:

    • 做到了。我将 db.close 移到了 except 部分,现在它循环并写入数据库没有任何问题。谢谢!
    猜你喜欢
    • 2015-10-17
    • 2017-09-07
    • 1970-01-01
    • 1970-01-01
    • 2019-10-09
    • 2016-12-11
    • 1970-01-01
    • 2015-04-23
    • 2019-09-22
    相关资源
    最近更新 更多