我需要一種方法來訪問我的python3應用程序在內存中(':memory:')在命令行界面工具sqlite3中創建的數據庫。這個想法是爲用戶提供標準sqlite3工具的便利,而不是在python本身中重新實現sqlite shell。在python和sqlite3之間傳輸數據庫cli工具
同樣,我們的目標是:
數據庫中存儲在我的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()
在這種情況下,我需要一種方法來保存源碼-init名無論是在SQL或二進制打開的數據庫上進行的所有修改(在正常的...)格式。
編輯:一個解決辦法是讓用戶對數據庫做他的東西,然後他結束會話(.Q .quit .exit捕捉標準輸入)之前,我可以把一箇中介
.output outfile.sql
.dump
.quit
在文件系統上重定向整個數據庫(以及它的修改!),然後將創建的文件讀回python應用程序。但是,這是如此醜陋和不雅...
爲什麼要將數據庫保存在內存中?首先在臨時文件中打開它,並且讓Python和'sqlite3'交替使用同一個文件是不是更容易? – millimoose 2013-03-16 12:55:58
因爲在腳本本身旁邊不應該有任何文件。應用程序的目的是從腳本文件本身提取數據庫(aes encrypted和base64編碼)並將其讀入內存。數據庫中的信息非常敏感,不應該保存在文件系統中。 – 2013-03-21 09:11:51
在這種情況下,將數據庫轉儲到SQL文件中的建議令人困惑。在第一個建議的解決方案中使用'NamedTemporaryFile'也一樣。兩者具有完全相同的安全含義。 – millimoose 2013-03-21 10:03:54