Python - How to print Sqlite table

淺唱寂寞╮ 提交于 2021-02-04 17:38:09

问题


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

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?

Any help is appreciated!


回答1:


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

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



回答2:


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



来源:https://stackoverflow.com/questions/17015980/python-how-to-print-sqlite-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!