使用python中的数据库名称创建内存中的sqlite数据库 [英] Create in-memory sqlite database with database name in python

查看:76
本文介绍了使用python中的数据库名称创建内存中的sqlite数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用python中的名称创建多个内存中的sqlite数据库.

I want to create multiple in-memory sqlite databases with names in python.

在sqlite命令行中,可以使用以下语法来做到这一点:

In sqlite command line it's possible to do that with this syntax:

':memory:' AS database_name

但是在像这样的python连接字符串中使用它时:

but when using it in python conenction strings like this:

con = sqlite3.connect("':memory:' AS database_name")

获取错误.

我的问题是我们如何在内存数据库中创建多个访问它们的名称.

My problem is how can we create multiple in memory databases with names for accessing them.

我们如何在python中做到这一点?

How we could do that in python?

推荐答案

AS子句仅与一起使用ATTACH语句,但不适用于主数据库(始终命名为 main ).

The AS clause works only with the ATTACH statement, but not for the main database (which is always named main).

数据库的标识来自其文件名,因此无论如何更改数据库名称都无济于事.

And the identify of a database comes from its file name, so changing the database name would not help anyway.

要为内存数据库使用自定义文件"名称,请使用 URI文件名 mode 参数:

To use a custom "file" name for an in-memory database, use a URI file name with the mode parameter:

conn = sqlite3.connect("file:blah?mode=memory", uri=True)

但是要将另一个具有自定义数据库名称的内存数据库附加到同一连接,只需正常执行ATTACH:

But to attach another in-memory database with a custom database name to the same connection, just execute ATTACH normally:

conn.execute("ATTACH ':memory:' AS db2")

这篇关于使用python中的数据库名称创建内存中的sqlite数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆