【问题标题】:What is the purpose of create temporary databases in python sqlite3?在 python sqlite3 中创建临时数据库的目的是什么?
【发布时间】:2021-11-15 17:21:05
【问题描述】:
import sqlite3
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.executescript("""
create table person(
firstname,
lastname,
age
);
create table book(

title,
author,
published
);
insert into book(title, author, published)
values (
'Dirk Gently''s Holistic Detective Agency',
'Douglas Adams',
1987
);
""")
cur.execute("""
SELECT * FROM book
""")

print(conn)
conn.commit()
x=cur.fetchall()
print(x)

我参考了这本书,它给出了这样的代码。在这里,您可以看到提到的数据库名称为“:memory:”,这是什么意思?我以为它用于在 RAM 中创建临时数据库,但是当我执行此代码时,它正在运行,但是当 fetchall() 并打印它时,它显示 empty list 。什么是临时数据库的使用。另外,我在这里没有使用正常的 execute 方法。我在这里使用 exeutesscript 方法。你能帮帮我吗?

【问题讨论】:

  • 别的意思
  • 这里我使用的是executionscript方法,而不是execute方法。
  • 您在 Book 表中插入了一条记录,然后您从 Person 表中进行选择,该表确实是空的,因为您没有向其中插入任何记录。
  • 是的,我更正了。但我想在这里澄清一下临时数据库。

标签: python python-3.x database sqlite


【解决方案1】:

:memory 数据库的重点是操作数据库而不将数据持久化到磁盘。例如,您可以使用 sqlite3 来管理内存中的应用程序状态,同时让数据库的所有功能都可用。进程内缓存将是其中的一个特例。您可能只关心短时间内的数据,例如,在测试运行 (q&a) 期间,或者将 i/o 服务时间作为基准测试的变量。

executescript() 忽略每个https://github.com/python/cpython/blob/3.9/Modules/_sqlite/cursor.c 的选择结果,它说:

/* 执行语句,忽略 SELECT 语句的结果 */

executescript() 之后,将execute() 用于select 语句。我删除了未使用的 create person 并重新格式化了剩余的两条语句以提高可读性,但原始查询没有改变:

import sqlite3

conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.executescript("""
create table book(title, author, published);
insert into book(title, author, published) values (
  'Dirk Gently''s Holistic Detective Agency', 'Douglas Adams', 1987
);
""")

cur.execute("select * from book;")
print(cur.fetchall())

返回:

[("Dirk Gently's Holistic Detective Agency", 'Douglas Adams', 1987)]

【讨论】:

  • 我按照您的方式尝试,但不打印任何内容。请确定我正在使用临时数据库(:memory :),并且我在这里使用执行脚本。为什么有人在这里投票,直到没有人不能写出真正的答案?它是自动发生的吗?
  • 我用独立的代码更新了我的答案,而不仅仅是所需的差异,以及我运行它时收到的数据。
  • 好的,非常感谢。临时数据库有什么用?
  • 刚刚用该信息更新了我的答案:-)
猜你喜欢
  • 1970-01-01
  • 2015-09-09
  • 2011-05-29
  • 2012-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-07
  • 1970-01-01
相关资源
最近更新 更多