Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Way to avoid repetition?
#1
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.
Reply


Messages In This Thread
Way to avoid repetition? - by Tuxedo - Feb-14-2021, 08:16 PM
RE: Way to avoid repetition? - by Serafim - Feb-14-2021, 10:19 PM
RE: Way to avoid repetition? - by deanhystad - Feb-14-2021, 10:22 PM
RE: Way to avoid repetition? - by Tuxedo - Feb-15-2021, 05:28 PM
RE: Way to avoid repetition? - by SheeppOSU - Feb-15-2021, 09:10 PM
RE: Way to avoid repetition? - by Tuxedo - Feb-16-2021, 08:02 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  question about you want repetition this task loczeq 6 3,414 Mar-05-2020, 08:35 PM
Last Post: loczeq
  Random nr. no repetition & printing multiple lines Joey 7 2,881 Feb-05-2020, 04:23 PM
Last Post: Larz60+
  About generating N integer numbers without repetition Otbredbaron 3 3,939 Jan-30-2018, 12:08 PM
Last Post: Otbredbaron
  List repetition ashwin 3 3,867 May-24-2017, 12:57 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020