如何从sqlite3数据库打印数据?

时间:2019-02-26 10:04:19

标签: python sqlite

import sqlite3

def function():
with sqlite3.connect("test.db")as db:
    c = db.cursor()

index = 1
while index == 1:

    c.execute("CREATE TABLE IF NOT EXISTS data(name,age);")
    insert = "INSERT INTO data(name,age) VALUES ('JOHN',16)"
    c.execute(insert)
    db.commit()
    index += 1
    display()

def display():
with sqlite3.connect("test.db")as db:
    c = db.cursor()

c.execute("CREATE VIEW IF NOT EXISTS test_VIEW AS SELECT name, age FROM data")
db.commit()
c.execute("SELECT * FROM test_VIEW")

function = function()
output = display()

引用SQLite Views。我正在尝试从数据库中打印所有数据。但是从上面的示例代码中,我只能得到一个空白输出。我该怎么办?

2 个答案:

答案 0 :(得分:1)

您需要遍历结果。请参阅下面的完整模型。我已经对其进行了修改,以便可以使用pandas数据框很好地打印出来。:

import sqlite3
import pandas as pd

def function():
    with sqlite3.connect("test.db")as db:
        c = db.cursor()
        index = 1
        while index == 1:

            c.execute("CREATE TABLE IF NOT EXISTS data(name,age);")
            insert = "INSERT INTO data(name,age) VALUES ('JOHN',16)"
            c.execute(insert)
            db.commit()
            index += 1
            display()

def display():
    with sqlite3.connect("test.db")as db:
        c = db.cursor()
        c.execute("CREATE VIEW IF NOT EXISTS test_VIEW AS SELECT name, age FROM data")
        db.commit()  
        data_pd = pd.read_sql('SELECT * FROM test_VIEW',db)
        print data_pd


function = function()
output = display()

结果如下:

   name  age
0  JOHN   16

答案 1 :(得分:0)

您将不得不使用fetchall()方法

在显示功能中执行

query = c.execute("SELECT * FROM test_VIEW")
data = c.fetchall()
for d in data:
    print (d)