如何在python中打印SQLite查询的结果? [英] How to print the results of a SQLite query in python?

查看:48
本文介绍了如何在python中打印SQLite查询的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试打印此 SQLite 查询的结果,以检查它是否已将数据存储在数据库中.目前它只打印无.有没有办法在 Microsoft Word 或 LibreOffice 等程序中打开数据库.只是看它是否已将内容保存到数据库中.

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.

推荐答案

只有 SELECT 查询有行集.1 所以,如果你想看到你只是插入,你需要SELECT那一行.

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

精确选择刚插入的行的一种方法是使用 rowid 伪列.此列具有由数据库自动生成的唯一值,并且每个 INSERT 语句都会更新一个 lastrowid 光标上的属性.所以:

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())

这将打印出如下内容:

('Starfighter F-104G',)

这篇关于如何在python中打印SQLite查询的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆