【问题标题】:Python MySQLdb - do I have to close cursors and connections?Python MySQLdb - 我必须关闭游标和连接吗?
【发布时间】: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()

问题:

  1. 我使用相同的光标对象进行 2 次插入。这样可以吗?
  2. 我是否必须关闭连接、光标等,否则 Python 会在脚本结束后进行管理?

【问题讨论】:

  • 请参阅this question,了解有关cursor.close() 必要性的信息。

标签: python mysql python-3.x


【解决方案1】:
  1. 没关系。
  2. 您应该关闭连接。

【讨论】:

    猜你喜欢
    • 2012-11-16
    • 2015-03-08
    • 2014-01-01
    • 2011-07-02
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    • 2015-10-01
    • 2020-03-16
    相关资源
    最近更新 更多