python - 如何使用 sqlite 创建内存数据库?

标签 python python-2.7 sqlite

我正在尝试使用 Python 中的 sqlite3 创建一个内存数据库。

我创建了一个函数来创建一个 db 数据库文件并将信息存储到其中,并且 100% 正常工作。

但是尝试连接 :memory: 我遇到了一些问题。

我正在做的是:

import sqlite3

def execute_db(*args):
    db = sqlite3.connect(":memory:")
    cur = db.cursor()
    data = True
    try:
        args = list(args)
        args[0] = args[0].replace("%s", "?").replace(" update "," `update` ")
        args = tuple(args)
        cur.execute(*args)
        arg = args[0].split()[0].lower()
        if arg in ["update", "insert", "delete", "create"]: db.commit()
    except Exception as why:
        print why
        data = False
        db.rollback()
    db.commit()
    db.close()
    return data
  1. 创建姓名表

    execute_db("create table name(name text)")
    

    返回 True

  2. 往这张表中插入一些信息

    execute_db("insert into name values('Hello')")
    

    哪个返回了

    no such table: name
    False
    

为什么这行不通?它在我使用文件时有效:

db = sqlite3.connect("sqlite3.db")

最佳答案

每次调用该函数时都会创建一个 连接。每个连接调用都会生成一个新的内存数据库。

在函数外部创建连接,并将其传递给函数,或者创建一个 shared memory connection :

db = sqlite3.connect("file::memory:?cache=shared")

但是,当最后一个连接从内存中删除时,数据库将被删除;在您的情况下,每次函数结束时都会出现。

无需显式调用 db.commit(),只需使用数据库连接 as a context manager :

try:
    with db:
        cur = db.cursor()
        # massage `args` as needed
        cur.execute(*args)
        return True
except Exception as why:
    return False

如果没有异常,事务自动提交,否则回滚。请注意,提交仅读取数据的查询是安全的。

关于python - 如何使用 sqlite 创建内存数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38676691/

相关文章:

python - 如何获得 int 的 32 位二进制补码位模式?

python - Pandas 方法在整个 DataFrame 上应用函数

python - 在列表中的字典中显示列表值

c# - System.TypeInitializationException : The type initializer for 'SQLite.SQLiteConnection' threw an exception

python - python 中的时间戳 firebase - firebase.put() 中的参数

python-2.7 - 如何让Arduino从Python读取串口?

python - 从 python sys.path 中永久删除一些东西

当我将它放入函数中时,Python 脚本停止工作

C++, SQLite - 指向字符串指针的指针

Android:光标窗口已满