I try to apply Don't Repeat Yourself concept in python.
import sqlite3
# Start connection and create cursor
def startdb():
# 1. Create connection
conn = sqlite3.connect("books.db")
# 2. Create a cursor object
cur = conn.cursor()
# Commit and close db
def closedb():
# 4. Commit changes
conn.commit()
# 5. Close connections
conn.close()
# Connect python to db
def connect():
startdb()
# 3. Create table if does not exist
cur.execute("CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY, title text, author text, year integer, isbn integer)")
closedb()
# Insert data to db
def insert(title,author,year,isbn):
startdb()
# SQL queries to insert
cur.execute("INSERT INTO book VALUES (NULL,?,?,?,?)",(title,author,year,isbn))
closedb()
# View all datas
def view():
startdb()
cur.execute("SELECT * FROM book")
rows=cur.fetchall()
conn.close()
return rows
connect()
insert("The sea","John Tablet",1983,913123132)
print(view())
and apparently I got a Name Error
Traceback (most recent call last):
File "backend.py", line 45, in <module>
connect()
File "backend.py", line 25, in connect
cur.execute("CREATE TABLE IF NOT EXISTS b
ook (id INTEGER PRIMARY KEY, title text, auth
or text, isbn integer)")
NameError: name 'cur' is not defined
Based on my understanding, this means that startdb() function does not pass in the variable conn and cur
Based on what I search, I need to use a class with a __init__ function in it, Is there a better solution to use the startdb() and closedb() function?
__init__function would help in starting the db and recording thecuras an attribute of the current instance. If you are unfamiliar with all this, I would recommend reading up on classes / OOPS first.currandconnobjects or using globalcurrandconnobjects. And then after you get that working, refractor the code into a class.global curr = conn.cursor?globalstatement. Really, I think you could get aways with simply putting a single line at the top ofstartdb:global conn, cur. Using global variables is usually not the best approach. It leads to hard to debug and reason about code. It is better to pass things as arguments to functions and return them from functions. A class would allow you to encapsulate all of this into one object.