我是 Jupyter Notebook 的新手,但想学习它。目前我正在尝试使用 sql magic 进行一些基本的数据库操作。我可以建立连接并创建一个新表。但是当我尝试读出该表时,会发生此非特定错误。有人可以帮我吗?
我的“代码”:
import sys
print(sys.executable)
from sqlalchemy.engine import create_engine
import pandas as pd
%load_ext sql
#setup database connection
%sql postgresql://postgres:postgres@localhost:5432/rain
%%sql
CREATE TABLE people (first text, last text, drink text);
INSERT INTO people (first,last,drink)
VALUES
('zaphod','beeblebrox','pan galactic gargle blaster'),
('arthur','dent','tea'),
('ford','prefect','old janx spirit')
;
%sql select * from people;
错误:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[40], line 1
----> 1 get_ipython().run_cell_magic('sql', '', '\nselect * from people;\n')
File ~/.local/share/pipx/venvs/jupyterlab/lib/python3.12/site-packages/IPython/core/interactiveshell.py:2541, in InteractiveShell.run_cell_magic(self, magic_name, line, cell)
2539 with self.builtin_trap:
2540 args = (magic_arg_s, cell)
-> 2541 result = fn(*args, **kwargs)
2543 # The code below prevents the output from being displayed
2544 # when using magics with decorator @output_can_be_silenced
2545 # when the last Python token in the expression is a ';'.
2546 if getattr(fn, magic.MAGIC_OUTPUT_CAN_BE_SILENCED, False):
File ~/.local/share/pipx/venvs/jupyterlab/lib/python3.12/site-packages/sql/magic.py:219, in SqlMagic.execute(self, line, cell, local_ns)
216 return
218 try:
--> 219 result = sql.run.run(conn, parsed["sql"], self, user_ns)
221 if (
222 result is not None
223 and not isinstance(result, str)
(...)
226 # Instead of returning values, set variables directly in the
227 # user's namespace. Variable names given by column names
229 if self.autopandas:
File ~/.local/share/pipx/venvs/jupyterlab/lib/python3.12/site-packages/sql/run.py:374, in run(conn, sql, config, user_namespace)
372 if result and config.feedback:
373 print(interpret_rowcount(result.rowcount))
--> 374 resultset = ResultSet(result, config)
375 if config.autopandas:
376 return resultset.DataFrame()
File ~/.local/share/pipx/venvs/jupyterlab/lib/python3.12/site-packages/sql/run.py:116, in ResultSet.__init__(self, sqlaproxy, config)
114 list.__init__(self, sqlaproxy.fetchall())
115 self.field_names = unduplicate_field_names(self.keys)
--> 116 self.pretty = PrettyTable(self.field_names, style=prettytable.__dict__[config.style.upper()])
117 else:
118 list.__init__(self, [])
KeyError: 'DEFAULT'
从日志消息来看,prettyTable 抛出错误,可能与结果的呈现方式有关。 尝试设置此选项,这将以纯文本格式返回结果。
%config SqlMagic.style = 'PLAIN'
也尝试为 PrettyTable 设置此项
%config SqlMagic.style = 'DEFAULT'