SQLite and Python
SQLite and Python
%matplotlib inline
db = 'davidStuff.db'
def run_query(q):
with sqlite3.connect(db) as conn:
return pd.read_sql(q, conn)
def run_command(c):
with sqlite3.connect(db) as conn:
conn.isolation_level = None
conn.execute(c)
conn.execute('PRAGMA foreign_keys = ON;')
def show_tables():
q='''
SELECT name,type
FROM sqlite_master
WHERE type IN ("table","view");
'''
return run_query(q)
In [ ]:
In [7]: c = '''
CREATE TABLE
IF NOT EXISTS datetime_int (
d1 int
);
'''
run_command(c)
print(show_tables())
name type
0 datetime_int table
In [8]: c='''
INSERT INTO datetime_int (d1)
VALUES
(strftime('%s','now'));
'''
run_command(c)
https://localhost:8888/notebooks/SQLite.ipynb 1/3
3/19/2019 SQLite
In [9]: c= '''
SELECT
d1
FROM
datetime_int;
'''
print(run_query(c))
d1
0 1546318845
In [10]: c='''
SELECT
datetime(d1,'unixepoch')
FROM
datetime_int;
'''
print(run_query(c))
datetime(d1,'unixepoch')
0 2019-01-01 05:00:45
In [16]: c='''
INSERT INTO datetime_int (d1)
VALUES
(
datetime('now', 'localtime')
);
'''
run_command(c)
In [23]: c='''
SELECT
datetime(d1,'unixepoch')
FROM
datetime_int;
'''
print(run_query(c))
datetime(d1,'unixepoch')
0 2019-01-01 05:00:45
1 None
2 None
3 None
https://localhost:8888/notebooks/SQLite.ipynb 2/3
3/19/2019 SQLite
In [18]: c='''
SELECT
d1
FROM
datetime_int;
'''
print(run_query(c))
d1
0 1546318845
1 2018-12-31 21:09:08
In [21]: c='''
INSERT INTO datetime_int (d1)
VALUES
(
datetime('now')
);
'''
run_command(c)
In [22]: c='''
SELECT
d1
FROM
datetime_int;
'''
print(run_query(c))
d1
0 1546318845
1 2018-12-31 21:09:08
2 None
3 2019-01-01 05:12:09
In [ ]:
https://localhost:8888/notebooks/SQLite.ipynb 3/3