[英]How to print out data from sqlite3 database?
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視圖 。 我正在嘗試從數據庫中打印所有數據。 但是從上面的示例代碼中,我只能得到一個空白輸出。 我應該怎么做?
您需要遍歷結果。 請參閱下面的完整模型。 我已經對其進行了修改,以便可以使用pandas
dataframe很好地打印出來:
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
您將必須使用fetchall()
方法
在顯示功能中
query = c.execute("SELECT * FROM test_VIEW")
data = c.fetchall()
for d in data:
print (d)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.