Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to print the results of this SQLite query to check whether it has stored the data within the database. At the moment it just prints None. Is there a way to open the database in a program like Microsoft Word or LibreOffice. Just to see whether it has saved the content into the database.

import tkinter as tk
import sqlite3 as lite
import sys


class GUI(tk.Frame):
    def __init__(self, master=None, **kwargs):
        tk.Frame.__init__(self, master, **kwargs)

    self.var = tk.StringVar()
    entry = tk.Entry(self, textvariable=self.var)
    entry.pack()

    btn = tk.Button(self, text='read', command=self.read_entry)
    btn.pack()

    btn = tk.Button(self, text='write', command=self.write_entry)
    btn.pack()

def read_entry(self):
    #print(self.var.get())

def write_entry(self):
    self.var.set(self.var.get())
    con = lite.connect('RandomThings.db')
    cur = con.cursor()
    cur.execute("CREATE TABLE jetfighter(Name TEXT)")
    cur.execute("INSERT INTO jetfighter VALUES (?)", (self.var.get(),))
    #con.commit()
    print (cur.fetchone())
    cur.close()

def main():
    root = tk.Tk()
    root.geometry('200x200')
    win = GUI(root)
    win.pack()
    root.mainloop()

if __name__ == '__main__':
    main()

Thank you for helping me with my problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
184 views
Welcome To Ask or Share your Answers For Others

1 Answer

Only SELECT queries have row sets.1 So, if you want to see the row you just inserted, you need to SELECT that row.

One way to select exactly the row you just inserted is by using the rowid pseudo-column. This column has unique values that are automatically generated by the database, and every INSERT statement updates a lastrowid property on the cursor. So:

cur.execute("INSERT INTO jetfighter VALUES (?)", (self.var.get(),))
cur.execute("SELECT * FROM jetfighter WHERE rowid=?", (cur.lastrowid,))
print(cur.fetchone())

This will print out something like:

('Starfighter F-104G',)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...