Grant Williams
Grant Williams

Reputation: 21

str object is not callable when inserting into SQLite database

I am working on a temperature sensor network using onewire temperature sensors that runs on a Raspberry Pi 2. I am following this tutorial and as I was going along, I realized that his setup is for one temperature sensor, whereas my setup needs to work with multiple sensors.

As a result of having multiple sensors, I also need to be able to differentiate the sensors from one another. To do this, I want to have 3 columns in the SQLite table. I am encountering the error when I execute the Python script that is supposed to log the readout from the sensor, the date and time, and the sensor name.

Here is the problem, when I am configuring the python script to write three values to the table, I get an error.

Here is the code that I am getting an error when executing

#!/usr/bin/env python

import sqlite3

import os
import time
import glob

# global variables
speriod=(15*60)-1
dbname='/var/www/templog.db'

# store the temperature in the database
def log_temperature(temp):

    conn=sqlite3.connect(dbname)
    curs=conn.cursor()
    sensor1 = 'Sensor1'

    curs.execute("INSERT INTO temps values(datetime('now'), (?,?))" (temp, sensor1)) 

    # commit the changes
    conn.commit()

    conn.close()

Upvotes: 2

Views: 5118

Answers (2)

shuttle87
shuttle87

Reputation: 15954

"INSERT INTO temps values(datetime('now'), (?,?))" (temp, sensor1)

Breaking this down you will see that this creates a string and then the parenthesis appears to Python to be a function call. However this is nonsensical because you have a string that you are trying to call like it is a function. Hence the error you get about str not being callable, this is definitely a bit cryptic if you are not experienced with Python. Essentially you are missing a comma:

curs.execute("INSERT INTO temps values(datetime('now'), (?,?))", (temp, sensor1)) 

Now you will get the ? placeholders correctly filled in.

Often the "str is not callable" error will be a result of typos such as this or duplicated variable names (you think you are calling a function but the variable really contained a string), so start by looking for those problems when you see this type of error.

Upvotes: 6

Bhargav Rao
Bhargav Rao

Reputation: 52181

You have to put a , there:

curs.execute("INSERT INTO temps values(datetime('now'), (?,?))" , (temp, sensor1)) 

From the documentation

Put ? as a placeholder wherever you want to use a value, and then provide a tuple of values as the second argument to the cursor’s execute() method

As you can see you need to provide the tuple as the second argument to the function execute

Upvotes: 2

Related Questions