【问题标题】:calling variables in function by another function with database由另一个具有数据库的函数调用函数中的变量
【发布时间】: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()函数没有传入变量conncur

根据我的搜索,我需要使用一个包含__init__ 函数的类,有没有更好的解决方案来使用startdb()closedb() 函数?

【问题讨论】:

  • 是的,你需要把这些函数放到一个类中。 __init__ 函数将有助于启动数据库并将cur 记录为当前实例的属性。如果您不熟悉这一切,我建议您先阅读类/OOPS。
  • 您不需要类来执行此操作,尽管它是类的一个很好的用例。为了体验,我将使用函数来实现这一点,或者传递currconn 对象,或者使用全局currconn 对象。然后在你开始工作之后,将代码重构到一个类中。
  • @juanpa.arrivillaga 你的意思是创建类似global curr = conn.cursor 的东西?
  • @AdamLiam 这不是您使用global 语句的方式。真的,我认为您只需在startdb 的顶部放置一行即可逃脱:global conn, cur。使用全局变量通常不是最好的方法。它导致难以调试和推理代码。最好将事物作为参数传递给函数并从函数中返回。一个类将允许您将所有这些封装到一个对象中。

标签: python sql python-3.x sqlite


【解决方案1】:

正如@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())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-29
    • 2017-05-18
    • 1970-01-01
    • 2017-11-04
    • 1970-01-01
    • 2018-01-31
    • 1970-01-01
    相关资源
    最近更新 更多