python - 通过数据库的另一个函数调用函数中的变量

标签 python sql python-3.x sqlite

我尝试在 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()函数没有传入变量conncur

根据我的搜索,我需要使用一个带有 __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/

相关文章:

python - 从另一个数据框中减去一个 Pandas 数据框中的属性值

python - OpenCV中的imagesc相当于什么

如果加入 SQLite 棘手

sql - 选择整个表格但特定列中的唯一值

sql - 在 MS-Access 中比较日期时数据类型不匹配

python - python "with"语句怎么写?

python - 如果给定一个整数列表和一个名为 x 的数字,如何递归返回列表中每个第 x 个数字的总和

python - 有没有办法在一组日期范围之间定位数据框?

python - 在 pandas DataFrame 中存储纯 python datetime.datetime

python - 如何导入包含具有循环依赖的类的模块?