通过python将值插入mysql表示“str”对象不可调用

通过python将值插入mysql表示“str”对象不可调用,python,mysql,Python,Mysql,试图通过python将温度值输入mysql: import os import time import datetime import glob import MySQLdb from time import strftime os.system('modprobe w1-gpio') os.system('modprobe w1-therm') temp_sensor = '/sys/bus/w1/devices/28-000000000cff/w1_slave' # Variables

试图通过python将温度值输入mysql:

import os
import time
import datetime
import glob
import MySQLdb
from time import strftime

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
temp_sensor = '/sys/bus/w1/devices/28-000000000cff/w1_slave'

# Variables for MySQL
mydb = MySQLdb.connect(host="localhost", user="user",passwd="", db="db")
### cur = db.cursor()
mycursor = mydb.cursor() 

def tempRead():
    t = open(temp_sensor, 'r')
    lines = t.readlines()
    t.close()

    temp_output = lines[1].find('t=')
    if temp_output != -1:
        temp_string = lines[1].strip()[temp_output+2:]
        temp_c = float(temp_string)/1000.0
    return round(temp_c,1)

while True:
    temp = tempRead()
    print temp
    datetimeWrite = (time.strftime("%Y-%m-%d ") + time.strftime("%H:%M:%S"))
    print datetimeWrite
    sql = ("INSERT INTO readings (cffr) VALUES (%s);" (temp),)
    mycursor.execute(sql)

    mydb.commit()



print(cur.rowcount, "record inserted.")
运行上面的命令,我得到:

8.4
2020-03-02 14:03:25
Traceback (most recent call last):
  File "dallas123.py", line 33, in <module>
    sql = ("INSERT INTO readings (cffr) VALUES (%s);" (temp),)
TypeError: 'str' object is not callable
我尝试过对括号和逗号进行几次修改,但我对代码盲了,看不见树木。请问这个有什么办法

("INSERT INTO readings (cffr) VALUES (%s);" (temp),)
查询和临时值之间只有一个空格。temp后面有一个逗号

您可能打算在那里写入%,但坦率地说,这也不是真正正确的,因为它是一个SQL注入向量。相反,您应该为execute方法提供单独的查询和参数,以便它能够进行正确的转义:

mycursor.execute("INSERT INTO readings (cffr) VALUES (%s)", [temp])
sql=将cffr值%s插入读数中;温度,应为sql=插入到读数中cffr值%s;%临时雇员