首页 > 解决方案 > 如何从 sqlite3 数据库中打印数据?

问题描述

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 视图。我正在尝试从数据库中打印出我的所有数据。但是从上面的示例代码中,我只得到一个空白输出。我应该怎么做?

标签: pythonsqlite

解决方案


您需要遍历结果。请参阅下面的完整模型。我已经对其进行了修改,因此它可以使用数据框很好地打印出来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

推荐阅读