2015-03-08 65 views
-1

我試圖通過Python將詳細信息輸入到SQL數據庫中。我已經創建了字段爲customerID,firstname,surname,town和telephone的數據庫。'str'對象不可調用Python to SQL數據庫

運行此函數時,我得到錯誤「str」對象不可調用的行,我試圖插入變量的值。

import sqlite3 
#function used to add a new customer, once confirmed save the customer in a 
#customer list 
def add_customer(): 

    #open up the clients database 
    new_db = sqlite3.connect('clients.db') 

    #create a new cursor object to be able to use the database 
    c = clients_db.cursor() 
    print("Add customer") 
    firstname = "" 
    while len(firstname) == 0: 
     firstname = input("Enter the customer's first name: ") 
    surname = "" 
    while len(surname) == 0: 
     surname = input("Enter the customer's surname: ") 
    town = "" 
    while len(town) == 0: 
     town=input("Enter the customer's town: ") 
    telephone = '1' 
    while len(telephone) != 11: 
     while telephone[0] != '0': 
      telephone = input("Please enter the customer's telephone number: ") 
      if telephone[0] != '0': 
       print ("telephone numbers must begin with zero") 
      elif len(telephone) != 11: 
       print("must have 11 numbers") 

    #check that data has been entered 
    print(firstname,surname,town,telephone) 



    #insert data into the customer table 
    c.execute('INSERT INTO Customer VALUES (NULL, ?,?,?,?,)'(firstname, surname, town, telephone)) 

    print("Customer added successfully ...") 

    clients_db.commit() 
    clients_db.close() 

    if choice ==1: 
     another = input("Would you like to add another? yes [y] or no [n] --> ") 
     if another=='y': 
      add_customer() 
     else: 
      main_menu() 
+0

請註明**完全回溯**,免得你離開我們猜測在那裏發生的事情:

只需插入逗號那裏。 – 2015-03-08 21:54:59

回答

0

你忘了SQL語句字符串和參數之間用逗號:

c.execute('INSERT INTO Customer VALUES (NULL, ?,?,?,?,)'(firstname, surname, town, telephone)) 
#              ^

所以你有效地做到這一點:"some string"(arg1, arg2, ...),試圖把字符串作爲一個功能。尋求與錯誤的幫助時

c.execute(
    'INSERT INTO Customer VALUES (NULL, ?,?,?,?,)', 
    (firstname, surname, town, telephone)) 
相關問題