我需要一种方法来访问命令行接口工具python3中的内存(': memory :')中创建的数据库。这样做的目的是为用户提供标准sqlite3工具的方便,而不是在python中重新实现sqlite。
同样,目标是:
数据库在我的python程序中打开,在内存中->编辑/处理sqlite3 cli工具中的数据库->将(可能)修改过的数据库移回我的python程序。
我想要的是:
def sqlite_cli(self):
# Spawn the original sqlite3 cli interface
# Dump the database in a named temporary file. Read it back into
# memory. At close() the tempfile will be erased.
with tempfile.NamedTemporaryFile(delete=True) as tf:
for line in self.connection.iterdump():
tf.write(bytes(line, 'ascii'))
# Work with the database through sqlite3
subprocess.call(['sqlite3', '-init', tf.name])
# Read the potentially modified database
# !!!!!!!!!!!!!!!!
# Here happens the logic gap: The sqlite3 tool doesn't
# save modifications to the file opend as the -init argument.
# How can I save the modifications done within sqlite3 as a
# sql text file ready to be read back into the app?!
tf.seek(0)
edited_db = tf.read()
# Delete all tables residing in memory
try:
for t in ACCMAN_TABLES:
self.cursor.execute('DROP TABLE IF EXISTS %s' % t)
self.connection.commit()
# Add the (maybe) edited one
self.cursor.executescript(edited_db.decode(encoding='utf-8'))
self.connection.commit()
except sqlite3.Error as e:
logger.error("sqlite_cli(): %s" % e.args[0])
tf.close()在这种情况下,我需要一种方法来保存在 sqlite -init文件名打开的数据库上所做的所有修改,无论是在sql还是二进制(普通的.)中。文件系统.上的格式
编辑:一种解决方案是让用户在数据库上做他的事情,然后在他结束会话之前(捕获.q .quit .exit的stdin ),我可以发送一个中介。
.output outfile.sql
.dump
.quit重定向整个数据库(以及它的修改!)然后将创建的文件读入python应用程序。但这太丑太不雅了..。
发布于 2013-08-23 20:46:36
我不认为您会喜欢这个答案,但我会考虑在您的应用程序中编写“模型”,作为能够接收xml调用的“服务器”。这样,您的“控制器”(以及外部控制器)就可以访问数据库,并做您允许他们做的任何事情。很容易将类的方法公开为XML服务器。请参阅http://docs.python.org/2/library/xmlrpclib.html?highlight=xmlrpc#xmlrpclib
https://stackoverflow.com/questions/15448327
复制相似问题