Feb-14-2021, 08:16 PM
I'm playing around right now with sqlite and was wondering if there is some mechanism within Python to avoid repeated use of 'my_cursor' in the below snippet:
import sqlite3
conn = sqlite3.connect('employee.db')
my_cursor = conn.cursor()
my_cursor.execute("INSERT INTO employees2 VALUES ('Corey','Scagnasty',50000)")
my_cursor.execute("INSERT INTO employees2 VALUES ('Joe','Scagnasty',90000)")
my_cursor.execute("INSERT INTO employees2 VALUES ('Hiep','Arnold',32000)")
my_cursor.execute("SELECT * FROM employees2")
ans = my_cursor.fetchall()
print(ans)I'm an old VBA guy and there is a wonderful trick where you can do the following:import sqlite3
conn = sqlite3.connect('employee.db')
my_cursor = conn.cursor()
with my_cursor
.execute("INSERT INTO employees2 VALUES ('Corey','Scagnasty',50000)")
.execute("INSERT INTO employees2 VALUES ('Joe','Scagnasty',90000)")
.execute("INSERT INTO employees2 VALUES ('Hiep','Arnold',32000)")
.execute("SELECT * FROM employees2")
ans = .fetchall()
end with
print(ans)I know Python uses the 'with' keyword for other purposes, but I'd love to know if there is a way to streamline similar to the above.
