Python - 如何打印 Sqlite 表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17015980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:13:57  来源:igfitidea点击:

Python - How to print Sqlite table

pythondatabasesqlite

提问by starscape

Here I have some simple python code to query a sqlite3 database.

这里我有一些简单的 python 代码来查询 sqlite3 数据库。

import sqlite3 as lite

conn = lite.connect('db/posts.db')
cur = conn.cursor()

def get_posts():
    cur.execute("SELECT * FROM Posts")
    print(cur.fetchall())

get_posts()

I have already created the table Posts. When I run this I get no errors, and it just prints out []. I know that the table Posts isn't empty, I created it in a REPL. Why is this not working?

我已经创建了表Posts。当我运行它时,我没有收到任何错误,它只是打印出[]. 我知道 Posts 表不是空的,我是在 REPL 中创建的。为什么这不起作用?

Any help is appreciated!

任何帮助表示赞赏!

采纳答案by Martin

Use a context manager, so you don′t have to commit!

使用上下文管理器,因此您不必提交!

def get_posts():
    with conn:
        cur.execute("SELECT * FROM Posts")
        print(cur.fetchall())

回答by starscape

Turns out I just forgot to use conn.commit(). Hope this helps someone.

原来我只是忘记使用conn.commit(). 希望这可以帮助某人。