Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - How to print Sqlite table

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!

like image 936
starscape Avatar asked Jun 10 '13 01:06

starscape


People also ask

How to create a SQLite table from Python?

Create SQLite table from Python. Refer to Python SQLite database connection to connect to SQLite database. Next, prepare a SQLite SELECT query to fetch rows from a table. You can select all or limited rows based on your requirement. Next, use a connection.cursor () method to create a cursor object. This method returns a cursor object.

How to use SELECT statement in Python SQLite?

In this article, we will discuss, select statement of the Python SQLite module. This statement is used to retrieve data from an SQLite table and this returns the data contained in the table. In SQLite the syntax of Select Statement is: SELECT * FROM table_name;

How to fetch rows from a table in SQLite?

Next, prepare a SQLite SELECT query to fetch rows from a table. You can select all or limited rows based on your requirement. Next, use a connection.cursor () method to create a cursor object. This method returns a cursor object. The Cursor object is required to execute the query. Execute the select query using the cursor.execute (query) method.

Is it possible to print query results in SQLite3?

The sqlite3 docs sneak that into an example about input sanitization, and that's it. No later section for printing query results or anything. Super confusing.


1 Answers

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

def get_posts():
    with conn:
        cur.execute("SELECT * FROM Posts")
        print(cur.fetchall())
like image 87
Martin Avatar answered Sep 23 '22 04:09

Martin