【发布时间】:2017-07-28 15:51:36
【问题描述】:
我尝试在 python 中应用 Don't Repeat Yourself 概念。
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())
显然我遇到了名称错误
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
根据我的理解,这意味着startdb()函数没有传入变量conn和cur
根据我的搜索,我需要使用一个包含__init__ 函数的类,有没有更好的解决方案来使用startdb() 和closedb() 函数?
【问题讨论】:
-
是的,你需要把这些函数放到一个类中。
__init__函数将有助于启动数据库并将cur记录为当前实例的属性。如果您不熟悉这一切,我建议您先阅读类/OOPS。 -
您不需要类来执行此操作,尽管它是类的一个很好的用例。为了体验,我将使用函数来实现这一点,或者传递
curr和conn对象,或者使用全局curr和conn对象。然后在你开始工作之后,将代码重构到一个类中。 -
@juanpa.arrivillaga 你的意思是创建类似
global curr = conn.cursor的东西? -
@AdamLiam 这不是您使用
global语句的方式。真的,我认为您只需在startdb的顶部放置一行即可逃脱:global conn, cur。使用全局变量通常不是最好的方法。它导致难以调试和推理代码。最好将事物作为参数传递给函数并从函数中返回。一个类将允许您将所有这些封装到一个对象中。
标签: python sql python-3.x sqlite