2017-03-08 55 views
2

我嘗試應用不重複自己在python中的概念。通過另一個函數調用變量在數據庫中的功能

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()函數?

+0

是的,你需要把這些功能整合到一個類。 '__init__'函數可以幫助啓動數據庫並將'cur'記錄爲當前實例的一個屬性。如果你不熟悉這一切,我會建議先閱讀課程/ OOPS。 –

+0

你不需要一個類來做到這一點,儘管它對於一個類來說是一個很好的用例。爲了體驗,我將使用函數來實現此功能,並傳遞'curr'和'conn'對象或使用全局'curr'和'conn'對象。然後,在你完成這個工作之後,將代碼摺疊成一個類。 –

+0

@ juanpa.arrivillaga你的意思是創建像'全球curr = conn.cursor'嗎? –

回答

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()) 
相關問題