Last active
May 3, 2020 14:11
-
-
Save MichaelCurrin/8105070b9e580342c380a9c42f1d97e1 to your computer and use it in GitHub Desktop.
Insert tweet data into a database using SQLite
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Python SQLite demo. | |
The sqlite3 library is a Python builtin. Read more in the Python 3 docs: | |
https://docs.python.org/3/library/sqlite3.html | |
See also the SQLite docs: | |
https://www.sqlite.org/docs.html | |
""" | |
import sqlite3 | |
conn = sqlite3.connect('db.sqlite') | |
cur = conn.cursor() | |
create_sql = """ | |
CREATE TABLE IF NOT EXISTS tweet( | |
id INTEGER PRIMARY KEY, | |
status_id INTEGER, | |
screen_name VARCHAR(30), | |
message VARCHAR(255) | |
) | |
""" | |
cur.execute(create_sql) | |
conn.commit() | |
# Mock data that would be fetched from the API. | |
# Note each item in the list is a list. | |
tweets = [ | |
[123, "foo", "Hello, world!"], | |
[124, "bar", "Hello, Tweepy!"], | |
] | |
# Note that id is not known upfront but can be left to autoincrement by specifying NULL. | |
insert_sql = """ | |
INSERT INTO tweet VALUES (NULL, ?, ?, ?) | |
""" | |
cur.executemany(insert_sql, tweets) | |
fetch_sql = """ | |
SELECT * | |
FROM tweet | |
""" | |
cur.execute(fetch_sql) | |
print(cur.fetchall()) | |
conn.commit() | |
conn.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment