在Jupyter Notebook中使用ipython-sql时如何创建自定义Sqlite UDF?

时间:2019-07-03 13:46:50

标签: python sql sqlite jupyter-notebook jupyter

我将如何在Jupyter / iPython中使用ipython-sql(https://github.com/catherinedevlin/ipython-sql)创建自定义SQLite UDF 或另一个iPython SQL魔术库?

我正在尝试做这样的事情...

%load_ext sql
%sql sqlite:///

%sql create table example(col text)
%sql insert into example (col) values ('stuff')

to_upper = lambda x: x.upper()

%sql select upper(col) from example

使用sqlite3 Python库时,应该...

from sqlalchemy import create_engine

conn = create_engine('sqlite://')
conn.execute('create table example(col text)')
conn.execute("insert into example values ('stuff')")

to_upper = lambda x: x.upper()

connection = conn.raw_connection()
connection.create_function('to_upper', 1, to_upper)
print(conn.execute("select to_upper(col) col from example").fetchall()[0][0])

任何想法?

1 个答案:

答案 0 :(得分:0)

%load_ext sql
%sql sqlite:///

%sql create table example(col text)
%sql insert into example (col) values ('stuff')

to_upper = lambda x: x.upper()

x=%sql -l
connection=x['sqlite://'].session.connection.connection

connection.create_function('to_upper', 1, to_upper)

%sql select upper(col) from example