I thought that I would try to connect the sqlite db function to the function instead of copying / pasting ~ 6 lines needed to connect and execute the query around the place. I would like to make it universal, so I can use the same function to create / select / insert / etc ...
Below I have tried. The "INSERT" and "CREATE TABLE" queries work, but if I make a "SELECT" query, how can I work with the values ββthat it selects outside the function?
Usually I want to print the values ββthat it gets, as well as do other things with them.
When I do this as shown below, I get an error
Traceback (most recent call last): File "C:\Users\steini\Desktop\py\database\test3.py", line 15, in <module> for row in connection('testdb45.db', "select * from users"): ProgrammingError: Cannot operate on a closed database.
So, I think the connection should be open, so I can get the values ββfrom the cursor, but I need to close it so that the file is not always locked.
Here is my test code:
import sqlite3 def connection (db, arg, cubby): conn = sqlite3.connect(db) conn.execute('pragma foreign_keys = on') cur = conn.cursor() cur.execute(arg) for row in cur: cubby.append(row) conn.commit() conn.close() cubby=[] connection('testdb.db', "create table users ('user', 'email')", cubby) connection('testdb.db', "insert into users ('user', 'email') values ('joey', ' foo@bar ')", cubby) for row in connection('testdb45.db', "select * from users", cubby): print row
How can I do this job?
EDIT: the code has changed a bit, so the cur values ββthat it adds to the external list, but still pretty bad
Steinthor.palsson
source share