【发布时间】:2014-09-25 17:46:11
【问题描述】:
我是 Python 新手。
我编写了一个简单的脚本,它在我的 Raspberry Pi 上每分钟运行一次,并将一些数据记录到 MySQL 5.5 数据库中。
脚本如下所示:
#!/usr/bin/python
import MySQLdb as mdb
from MyADCPi import ADCPi
import time
import os
con = mdb.connect('localhost','pi','pi','pi')
#initialize MCP3424 ADC in 18 bit mode
adc = ADCPi(18)
# initialize cursor
cur = con.cursor()
# measure LM35 output voltage and calculate temperature
# 1'C = 10mV, 1V = 100'C
temp = adc.readVoltage(1)*100
# log temperature
cur.execute("INSERT INTO data(channel, value) values(1,"+str(temp)+")")
# measure MPX4115 voltage and calculate pressure
# (19.5/7.5) is voltage divider
# vs is sensor supply voltage
# (vo/vs + 0.095)/0.0009 comes from formula in MPX4115 datasheet
vo = adc.readVoltage(2)*(19.5/7.5)
vs = 4.8
press = (vo/vs + 0.095)/0.0009
# log pressure
cur.execute("INSERT INTO data(channel, value) values(2,"+str(press)+")")
con.commit()
问题:
- 我使用相同的光标对象进行 2 次插入。这样可以吗?
- 我是否必须关闭连接、光标等,否则 Python 会在脚本结束后进行管理?
【问题讨论】:
-
请参阅this question,了解有关
cursor.close()必要性的信息。
标签: python mysql python-3.x