2013-07-28 30 views
0

然而,當一個簡單的ddl程序在響應使用y或n時出現名稱錯誤,例如說。 y沒有定義。當我更改代碼以使用1或2時,程序運行良好。我很困惑如何y或n可以拋出一個名稱錯誤,我曾嘗試將輸入結果定義爲一個字符串,但它仍然給名稱錯誤。Python - DDL程序if語句在使用y/n而不是1/2時導致名稱錯誤

import sqlite3 
# 
def create_table(db_name,table_name,sql): 
    with sqlite3.connect(db_name) as db: 
     cursor = db.cursor() 
     cursor.execute('select name from sqlite_master where name=?',(table_name,)) 
     result = cursor.fetchall() 
     keep_table = True 
     if len(result) == 1: 
#Problem area 
      response = input('The table {0} already exists, do you wish to overide? (y/n): '.format(table_name)) 
      if response == 'y': 
#Problem area end 
       keep_table = False 
       cursor.execute('drop table if exists {0}'.format(table_name)) 
       print('Table overwritten') 
       db.commit() 
      else: 
       print('Table kept') 
     else: 
      keep_table = False 
     if not keep_table: 
      cursor.execute(sql) 
      db.commit() 
# 
if __name__ == '__main__': 
    db_name = 'coffee_shop.db' 
    sql = '''create table Product 
      (ProductID integer, 
      Name varchar(30), 
      Price real, 
      primary key(ProductID))''' 
    create_table(db_name,'Product',sql) 

錯誤消息

The table Product already exists, do you wish to overide? (y/n): y 
Traceback (most recent call last): 
    File "coffee_shop_v2.db", line 34, in <module> 
    create_table(db_name,'Product',sql) 
    File "coffee_shop_v2.db", line 13, in create_table 
    response = input('The table {0} already exists, do you wish to overide? (y/n): '.format(table_name)) 
    File "<string>", line 1, in <module> 
NameError: name 'y' is not defined 
+0

一些您指定的標籤是不相關的你問的具體問題。請考慮刪除這些。此外,你的問題區域顯然不是ddl。如果你也看到了錯誤信息,那對你有幫助。 – kashyap

+0

爲什麼不用'?'和第二個'cursor.execute'?使用直接的'.format'會增加發生SQL注入漏洞的機率。 – nneonneo

回答