Python 如何从sqlite3数据库打印数据?
参考。我正试图打印出数据库中的所有数据。但是从上面的示例代码中,我只得到一个空白输出。我该怎么办?您必须使用Python 如何从sqlite3数据库打印数据?,python,sqlite,Python,Sqlite,参考。我正试图打印出数据库中的所有数据。但是从上面的示例代码中,我只得到一个空白输出。我该怎么办?您必须使用fetchall()方法 在显示功能中 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)
fetchall()
方法
在显示功能中
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()
您需要循环查看结果。见下面的完整模型。我对其进行了修改,以便使用
pandas
dataframe可以很好地打印出来:
query = c.execute("SELECT * FROM test_VIEW")
data = c.fetchall()
for d in data:
print (d)
结果如下:
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()
哦,现在可以了。有没有办法像下面那样打印出来?姓名年龄------约翰16岁
name age
0 JOHN 16