You are on page 1of 4

Harri son i n Graphi ng / Chart i ng Mat pl ot l i b | June 14, 2014

SQLite Part 2:
Dynamically Inserting
into a Database +
timestamps
Python databases with SQLite Part 2,
inserting data.
This is part 7 of the massive Matplotlib tutorial series offered
here.
This can also just be a stand-alone mini-series on Pythons SQL
module sqlite, though you should start at part 1 if you have not!



Python Programming Tutorials Image Recognition Data Analysis
Robotics Django Web Development Matplotlib (Graphing) PyGame
Sentiment Analysis / NLP Basics
In the previous video, we learned how to create a database
connection, which will create the database if it does not exist. We
then learned how to create a table, which we learned that we should
only do once! Then, we inserted some data into our sqlite database,
but we probably found this to be somewhat silly, as we still had to
type it all by hand. It will become necessary eventually to dynamically
insert data into a database via your program and variables that it
discovers. This tutorial covers how to do just that! As an added bonus,
we talk briefly about the conversion of unix time stamps to
datestamps.
Here is the sample code:
1
2
3
4
5
6
7
8
import sqlite3

import datetime
import time


conn = sqlite3.connect('tutorial.db')
c = conn.cursor()
In the next tutorial, we cover how to read from an SQL database
with Python.

Write a Comment
RELATED CONTENT BY TAG DATABASE MATPLOTLIB PYTHON SQLITE
Harrison Published
June 1 4, 201 4
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

def tableCreate():
c.execute("CREATE TABLE stuffToPlot(ID INT, unix REAL, datestamp TEXT,
keyword TEXT, value REAL)")


def dataEntry():
c.execute("INSERT INTO stuffToPlot VALUES(1, 1365952181.288,'2013-04-14
10:09:41','Python Sentiment',5)")
c.execute("INSERT INTO stuffToPlot VALUES(2, 1365952257.905,'2013-04-14
10:10:57','Python Sentiment',6)")
c.execute("INSERT INTO stuffToPlot VALUES(3, 1365952264.123,'2013-04-14
10:11:04','Python Sentiment',4)")
conn.commit()

idfordb = 4
keyword = 'Python Sentiment'
value = 7

def dataEntry2():
date = str(datetime.datetime.fromtimestamp(int(time.time())).strftime('%Y-
%m-%d %H:%M:%S'))
c.execute("INSERT INTO stuffToPlot (ID, unix, datestamp, keyword, value)
VALUES (?, ?, ?, ?, ?)",
(idfordb, time.time(), date, keyword, value))
conn.commit()
Independent Publisher empowered by WordPress