用数据库的另一个函数调用函数中的变量

时间:2017-03-08 07:19:48

标签: python sql python-3.x sqlite

我尝试在python中应用Do not 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()函数?

1 个答案:

答案 0 :(得分: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())