我尝试在 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()
函数?
最佳答案
如@juanpa.arrivillaga 所述,您需要一个全局声明。 你在 sqlite3 查询中犯了一个错误,你忘记了 SQL 创建表查询中的年份列
import sqlite3
# Start connection and create cursor
def startdb():
global conn, cur
# 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())
关于python - 通过数据库的另一个函数调用函数中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42665233/