通过ipython访问rdbms
hops-ipython-sql的Python项目详细描述
示例
In[1]:%load_extsqlIn[2]:%%sqlpostgresql://will:longliveliz@localhost/shakes...:select*fromcharacter...:whereabbrev='ALICE'...:Out[2]:[(u'Alice',u'Alice',u'ALICE',u'a lady attending on Princess Katherine',22)]In[3]:result=_In[4]:print(result)charidcharnameabbrevdescriptionspeechcount=================================================================================AliceAliceALICEaladyattendingonPrincessKatherine22In[4]:result.keysOut[5]:[u'charid',u'charname',u'abbrev',u'description',u'speechcount']In[6]:result[0][0]Out[6]:u'Alice'In[7]:result[0].descriptionOut[7]:u'a lady attending on Princess Katherine'
第一次连接后,可以省略连接信息:
In [8]: %sql select count(*) from work Out[8]: [(43L,)]
可以维护到多个数据库的连接。你可以参考 一个现有连接,通过 username @ 数据库
In[9]:%%sqlwill@shakes...:selectcharname,speechcountfromcharacter...:wherespeechcount=(selectmax(speechcount)...:fromcharacter);...:Out[9]:[(u'Poet',733)]In[10]:print(_)charnamespeechcount======================Poet733
如果未提供连接字符串, %sql 将提供现有连接的列表; 但是,如果尚未建立连接,并且环境变量 database\u url 可以使用。
为了安全访问,您可以动态访问您的凭据(例如,从您的系统环境或 getpass.getpass ),以避免将密码存储在笔记本本身中。在任何变量之前使用 $ 在 %sql 命令中访问它。
In[11]:user=os.getenv('SOME_USER')....:password=os.getenv('SOME_PASSWORD')....:connection_string="postgresql://{user}:{password}@localhost/some_database".format(user=user,password=password)....:%sql$connection_stringOut[11]:u'Connected: some_user@some_database'
您可以在一个单元格中使用多个SQL语句,但是 只看到最后一个查询结果,所以 对于没有输出的语句是有意义的
In[11]:%%sqlsqlite://....:CREATETABLEwriter(first_name,last_name,year_of_death);....:INSERTINTOwriterVALUES('William','Shakespeare',1616);....:INSERTINTOwriterVALUES('Bertold','Brecht',1956);....:Out[11]:[]
绑定变量(绑定参数)可以在"命名"(:x)样式中使用。 使用的变量名应在本地命名空间中定义
In[12]:name='Countess'In[13]:%sqlselectdescriptionfromcharacterwherecharname=:nameOut[13]:[(u'mother to Bertram',)]
为了方便起见,支持对结果集进行dict样式的访问,使用 最左边的列用作键,用于唯一值。
In[14]:result=%sqlselect*fromwork43rowsaffected.In[15]:result['richard2']Out[15]:(u'richard2',u'Richard II',u'History of Richard II',1595,u'h',None,u'Moby',22411,628)
结果也可以作为字典的迭代器来检索( result.dicts() ) 或者一个单字典,每个键有一个标量值元组( result.dict() )