this is my first time learning sqlite and I'm still wondering how to do it. I ended up with this sort of library code:
database_path = "userfiles\databases"
def connect(database):
"""Open a connection and a cursor to the database file provided."""
conexion = sqlite3.connect(database_path + database + ".db")
cursor = conexion.cursor()
return {"conexion":conexion, "cursor":cursor}
def disconnect(conexion, cursor, savechanges=False):
"""Disconnect from database, closing the cursor first.
and saving the cursor data with a commit."""
cursor.close()
if savechanges:
conexion.commit()
conexion.close()
def build_sqlquery(**sqlquery):
"""Create the query that we will send to the sqlite file."""
if "select" in sqlquery:
query_built = "SELECT " + str(sqlquery["select"])
if "fromtable" in sqlquery:
query_built = query_built + " FROM " + str(sqlquery["fromtable"])
elif "insert_into" in sqlquery:
query_built = "INSERT INTO " + str(sqlquery["insert_into"])
if "values" in sqlquery:
query_built = query_built + " VALUES " + str(sqlquery["values"])
elif "delete" in sqlquery:
query_built = "DELETE FROM " + str(sqlquery["delete"])
elif "update" in sqlquery:
query_built = "UPDATE " + str(sqlquery["update"])
if "set_values" in sqlquery:
query_built = query_built + " SET " + str(sqlquery["set_values"])
if "where" in sqlquery:
query_built = query_built + " WHERE " + str(sqlquery["where"])
if "limit" in sqlquery:
query_built = query_built + " LIMIT " + str(sqlquery["limit"])
return query_built
def findifexists(cursor, pydata=False, **sqlquery):
"""Query the params into a working sqlite query and
execute the result, including the pydata if found."""
query_built = build_sqlquery(sqlquery)
if not pydata:
cursor.execute(query_built)
else:
cursor.execute(query_built, pydata)
datos_de_registro = cursor.fetchone() is not None
return datos_de_registro
And then, once that library is created, I executed my queries like this:
conn = connect("food")
exists = findifexists(conn["cursor"], (value1, value2, value3, condition1),
select="(?,?,?)",
fromtable="mytable",
where="Something = ?")
disconnect(conn["conexion"], conn["cursor"])
if exists:
print("Yes, it exists")
else:
print("Nope")
Now my concern is that it feels like re-inventing the wheel, where I could just throw an SQLite query directly at the caller without building it up in the build_sqlquerymethod.
What do you think about it? What cons or pros does this have? Also: If I want to execute multiple queries, It's okay to keep a conection and a cursor open to execute them one after another before closing them? Or should I connect, save something, disconnect, and then connect again and repeat the procces?