Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python script to create a sqlite DB and table entries
import sqlite3 as lite
import sys
conn = lite.connect('blog_posts.db')
# This will be called only the first time to create the table by running "python db_init_sqlite.py create"
def create_table():
with conn:
cursor = conn.cursor()
cursor.execute("CREATE TABLE posts (date TEXT, title TEXT PRIMARY KEY, content TEXT);")
conn.commit()
# This can be called many times as long as the title is unique
def insert_post(date, title, filename):
with conn:
cursor = conn.cursor()
cursor.execute("INSERT INTO posts VALUES('{0}','{1}', '{2}')".format(date, title, filename))
conn.commit()
# function to print the posts
def run_select_title_query(title):
with conn:
cursor = conn.cursor()
cursor.execute("SELECT content FROM posts WHERE title=?", (title,))
content = cursor.fetchall()
content = str(content).strip("[('',)]")
with open(content, "r") as file:
file_content = file.readlines()
print(file_content) # this will be html code representing the content of the file.
if __name__ == "__main__":
if len(sys.argv) > 1:
if sys.argv[1] == "create":
# if argv has "create", then create the table.
create_table()
# insert the entries on to the database
insert_post("July 29th 2017", "Hello World", "hello_world.html")
# Run select query to list contents of the file
run_select_title_query("Hello World")
conn.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.