With the excellent ipython-sql jupyter extension installed, it becomes very easy to connect to SQL database backends. This notebook demonstrates how to do this.
Note that this is a Python 2 notebook.
First, we need to activate the extension:
In [46]:
%load_ext sql
There are warnings, but that's okay - this happens a lot these days due to the whole ipython/jupyter renaming process. You can ignore them.
Using the bash shell (not a notebook!), follow the instructions at the SW Carpentry db lessons discussion page to get the survey.db file. This is a sqlite3 database.
I recommend following up with the rest of the instructions on that page to explore sqlite3.
This part is easy, just connect like so (assuming the survey.db file is in the same directory as this notebook):
In [47]:
%sql sqlite:///survey.db
Out[47]:
In [48]:
%sql SELECT * FROM Person;
Out[48]:
You should be able to execute all the standard SQL queries from the lesson here now. Note that you can also do this on the command line.
Note specialized sqlite3 commands like ".schema" might not work.
In [49]:
%sql mysql://mysqluser:mysqlpass@localhost/
Out[49]:
note if you get an error about MySQLdb not being installed here, enter this back in your bash shell:
% sudo pip install mysql-python
If it asks for your password, it's "vagrant".
After doing this, try executing the above cell again. You should see:
u'Connected: mysqluser@'
...if it works.
In [50]:
%sql CREATE DATABASE week3demo;
Out[50]:
Now that we've created the database week3demo, we need to tell MySQL that we want to use it:
In [51]:
%sql USE week3demo;
Out[51]:
But there's nothing in it:
In [52]:
%sql SHOW TABLES;
Out[52]:
From here we need to create a first table. Let's recreate the Person table from the SW Carpentry db lesson, topic 1.
In [53]:
%%sql
CREATE TABLE Person
(ident CHAR(10),
personal CHAR(25),
family CHAR(25));
Out[53]:
In [54]:
%sql SHOW TABLES;
Out[54]:
In [55]:
%sql DESCRIBE Person;
Out[55]:
In [56]:
%%sql
INSERT INTO Person VALUES
("dyer", "William", "Dyer"),
("pb", "Frank", "Pabodie"),
("lake", "Anderson", "Lake"),
("roe", "Valentina", "Roerich"),
("danforth", "Frank", "Danforth")
;
Out[56]:
In [57]:
%sql SELECT * FROM Person;
Out[57]:
In [58]:
%sql SELECT * FROM Person WHERE personal = "Frank";
Out[58]:
In [59]:
result = _
print result
You can even assign it to a Pandas dataframe:
In [60]:
df = result.DataFrame()
In [61]:
df
Out[61]:
In [62]:
%sql DROP TABLE Person;
Out[62]:
In [63]:
%sql SHOW TABLES;
Out[63]:
And to get rid of a whole database, use DROP DATABASE:
In [64]:
%sql DROP DATABASE week3demo;
Out[64]:
In [65]:
%sql SHOW DATABASES;
Out[65]: