2015-03-08 93 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))