Python插入SQLi

2024-04-25 06:45:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下问题:

我想使用SQLite3和Python插入RPI的温度。 我要使用的python脚本:

import subprocess
import os
import sqlite3 as lite
import datetime
import sys
import time

def get_temperature():
    "Returns the temperature in degrees C"
    try:
        s = subprocess.check_output(["cat","/sys/class/thermal/thermal_zone0/temp"])
        return s[:-1]
    except:
        return 0



try:
    con = lite.connect('/www/auslastung.s3db')
    cur = con.cursor()

    temp = int(get_temperature())
    zeit = time.strftime('%Y-%m-%d %H:%M:%S')

    cur.execute("INSERT INTO 'temperatur' ('Wert', 'Zeit') VALUES (%s, %s)", (temp, zeit))

    con.commit()

except lite.Error, e:

    if con:
       con.rollback()
    print "Error %s" % e.args[0]
    sys.exit(1)

finally:

    if con:
       con.close()

每次我想运行这个时,我都会得到一个错误:

^{pr2}$

我该怎么解决这个问题?在


Tags: importgetreturntimesyslitecontemp
2条回答

也可以替换:

在当前执行(“插入'temperature'('Wert','Zeit')值(%s,%s)”,(temp,Zeit))

在当前执行(“插入'temperature'('Wert','Zeit')值(%s,%s)”%(temp,Zeit))

@nwk或我的答案应该根据偏好而起作用。在

更换

cur.execute("INSERT INTO 'temperatur' ('Wert', 'Zeit') VALUES (%s, %s)", (temp, zeit))

^{pr2}$

你的finally子句也有问题。如果con一开始就没有分配给NameError: name 'con' is not defined,它将失败,并出现错误con(例如,如果目录/www/不存在,那么con = lite.connect('/www/auslastung.s3db')失败)。您可以执行以下操作来避免此问题:

con = None
try:
    # ...
except lite.Error, e:
    if con is not None:
       con.rollback()
    # ...
finally:
    if con is not None:
       con.close()

相关问题 更多 >