首页 > 解决方案 > 使用 pd.read_sqlite 读取远程服务器中的 sqlite 文件

问题描述

是否可以通过 python 中的 ssh 读取位于远程服务器中的 sqlite3 数据库?到目前为止,我必须将文件从服务器复制到我的本地计算机然后打开它,这不是很有效......我正在寻找这样的东西:

query = 'SELECT * FROM table'
with sqlite3.connect('user@server:path/to/sqlitefile') as conn:
   df = pd.read_sql(query, conn)

有可能在 Python 中做这样的事情吗?谢谢您的帮助!

标签: pythonpandassqlitessh

解决方案


我刚刚修改了@dan-web 的代码(对不起,我不知道如何引用他),现在它正在工作:

ssh = SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=hostname, username=username)
stdin, stdout, stderr = ssh.exec_command('sqlite3 /path/to/file.sqlite "select * from table;"')
result = stdout.readlines()
if not result:
    result = stderr.readlines()
ssh.close()

你得到一个列表作为输出。我刚刚将列表转换为 Pandas DataFrame ...谢谢!


推荐阅读