简体   繁体   中英

inserting python variable data into sqlite table not saving

I'm querying a json on a website for data, then saving that data into a variable so I can put it into a sqlite table. I'm 2 out of 3 for what I'm trying to do, but the sqlite side is just mystifying. I'm able to request the data, from there I can verify that the variable has data when I test it with a print, but all of my sqlite stuff is failing. It's not even creating a table, much less updating the table (but it is printing all the results to the buffer for some reason) Any idea what I'm doing wrong here? Disclaimer: Bit of a python noob. I've successfully created test tables just copying the stuff off of the python sqlite doc

# this is requesting the data and seems to work
for ticket in zenpy.search("bananas"):
id = ticket.id
subj = ticket.subject
created = ticket.created_at
for comment in zenpy.tickets.comments(ticket.id):
    body = comment.body

# connecting to sqlite db that exists. things seem to go awry here
conn = sqlite3.connect('example.db')
c = conn.cursor()

# Creating the table table (for some reason table is not being created at all)
c.execute('''CREATE TABLE tickets_test
         (ticket id, ticket subject, creation date, body text)''')

# Inserting the variables into the sqlite table 
c.execute("INSERT INTO ticketstest VALUES (id, subj, created, body)")

# committing changes the changes and closing
c.commit()
c.close()

I'm on Windows 64bit and using pycharm to do this.

Your table likely isn't created because you haven't committed yet, and your sql fails before it commits. It should work when you fix your 2nd sql statement.

You're not inserting the variables you've created into the table. You need to use parameters. There are two ways of parameterizing your sql statement . I'll show the named placeholders one:

c.execute("INSERT INTO ticketstest VALUES (:id, :subj, :created, :body)", 
    {'id':id, 'subj':subj, 'created':created, 'body':body}
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM