Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

tkinter - How to print the results of a SQLite query in python?

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

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

1 Reply

0 votes
by (71.8m points)

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',)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...