Reputation: 3435
I'm trying to insert the results of a query into a table, but add a variable to the result set . I've looked at some similar questions and I think I am representing the query variables correctly but I am getting a "global variable not defined" error. Can you point me in the right direction? I'm guessing it has to do with the fact that I am trying to represent a SELECT statement with a variable, but I'm not sure how the syntax should look.
def main():
datadump()
d = datetime.date.today()
queryCurs.execute('SELECT * FROM data ORDER BY ac')
sqlresults = queryCurs.fetchall()
x,y,z = sqlresults
queryCurs.execute('INSERT INTO history VALUES (?,?,?,?)',
(d, x, y, z))
createDb.commit
Thanks!
Upvotes: 1
Views: 3242
Reputation: 879271
You don't need to make two SQL queries to do this. Instead, use an INSERT query of the form INSERT INTO ... SELECT ...:
conn=sqlite3.connect(...)
cursor=conn.cursor()
today = datetime.date.today()
sql='''
INSERT INTO history
SELECT ?, foo, bar, baz
FROM data
ORDER BY ac
'''
cursor.execute(sql,[today])
conn.commit()
Upvotes: 2