Created
June 26, 2020 08:10
-
-
Save PandaWhoCodes/2a7d014bc2c06f774b08ecbe30313409 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import sqlite3 | |
db_name = "database.db" | |
def create_connection(db_file): | |
""" create a database connection to the SQLite database | |
specified by db_file | |
:param db_file: database file | |
:return: Connection object or None | |
""" | |
conn = None | |
try: | |
conn = sqlite3.connect(db_file) | |
except Error as e: | |
print(e) | |
return conn | |
def create_tables(conn, create_table_sql): | |
""" create a table from the create_table_sql statement | |
:param conn: Connection object | |
:param create_table_sql: a CREATE TABLE statement | |
:return: | |
""" | |
try: | |
c = conn.cursor() | |
c.execute(create_table_sql) | |
conn.commit() | |
except Exception as e: | |
print("Tables could not be created:", e) | |
def run_query(query, args=[], conn=None): | |
""" create a table from the create_table_sql statement | |
:param conn: Connection object | |
:param query: a SQL query | |
:return: | |
""" | |
if not conn: | |
conn = create_connection(db_name) | |
cur = conn.cursor() | |
if query.lower().strip().startswith("select"): | |
cur.execute(query, args) | |
return cur.fetchall() | |
else: | |
cur.execute(query, args) | |
try: | |
conn.commit() | |
except Exception as e: | |
print("ERROR OCCURED WHILE DB COMMIT", e) | |
def insert_into_websites(url, website_text): | |
sql_update_users_table = """INSERT INTO website (url,website_text) VALUES (?, ? );""" | |
run_query(sql_update_users_table, [url, website_text]) | |
def get_site_content(url): | |
sql_query = """ | |
SELECT `website_text` FROM website WHERE | |
url= ?""" | |
return run_query(sql_query, [url]) | |
def create_db(db_file): | |
""" | |
A function used to create a database file to store all the data | |
""" | |
connection = create_connection(db_file) | |
sql_query = """ | |
CREATE TABLE IF NOT EXISTS website ( | |
id INTEGER PRIMARY KEY, | |
url text NOT NULL, | |
website_text text NOT NULL | |
); | |
""" | |
create_tables(conn=connection, create_table_sql=sql_query) | |
if __name__ == '__main__': | |
# create_connection(db_name) | |
# create_db(db_name) | |
# insert_into_websites("www.google.com", "this is google.com text") | |
print(get_site_content("www.google.com")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment