python - 如何从 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 视图。我正在尝试从数据库中打印出我的所有数据。但是从上面的示例代码中,我只得到一个空白输出。我应该怎么做?
解决方案
您需要遍历结果。请参阅下面的完整模型。我已经对其进行了修改,因此它可以使用数据框很好地打印出来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
推荐阅读
- flutter - Flutter:找不到 String.xml 文件
- c - (简而言之)它是如何工作的?
- ruby-on-rails - 如何绕过 validates_email_format_of 验证以保存 nil 电子邮件值?
- javascript - 无法向自己发出 POST 请求
- c++ - c++ 字符串中的字符被忽略
- docker - Azure 容器注册表是多区域的吗?
- python - 通过右键单击 UI 在 Maya 中运行脚本?
- audiokit - AKMIDICallbackInstrument 处理超过 16 个通道
- javascript - 在图像的特定位置绘制黑点
- javascript - 在 app.get(...) 中表达未定义的变量