Last active
May 26, 2020 07:24
-
-
Save ejdecena/ad8c6e570e6b0f444acd6ddd39d285db to your computer and use it in GitHub Desktop.
Execute a query in a SQLite-type database.
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
#!/usr/bin/env python3 | |
import sqlite3 | |
import typing | |
def execute_db_query(db_filename: str, query: str, parameters: tuple=()) \ | |
-> typing.Any: | |
"""Execute a query in a SQLite-type database. | |
Args: | |
db_filename: string with the name of the SQLite file. | |
query: strig with the SQL query. | |
parameters: tupla with the query parameters. | |
Returns: | |
a tuple of data in case of SELECT queries or an integer with the number of affected rows. | |
Use: | |
query = "INSERT INTO contacts VALUES (NULL, ?, ?);" | |
parameters = (namefield, numfield) | |
result = execute_db_query(query, parameters) | |
""" | |
with sqlite3.connect(db_filename) as conn: | |
cursor = conn.cursor() | |
query_result = cursor.execute(query, parameters) | |
conn.commit() | |
return query_result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment