语法错误我无法弄清楚? python3

时间:2017-05-20 12:13:11

标签: python-3.x syntax

这是我的计划。它告诉我语法错误的确切位置,但我完全不知道问题是什么:

K__ = sf^2+sn^2;

这是我收到的语法错误消息。我在代码中放了箭头,突出显示它指出的位置:

import sqlite3

def create_table(dbName, table_name, sql):
    with sqlite3.connect("ATM.db") 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:
            response = input("The table{0} already exists, do you wish to recreate? (y/n) \n".format(table_name))
            if response.lower() == "y":
                keep_table = False
                print("the {0} table will be recreated".format(table_name))
                cursor.execute("drop table if exists {0}".format(table_name))
                db.commit()
                insert_data()
            else:
                print("The existing table was kept")
                insert_data()
        else:
            keep_table = False
        if not keep_table:
>>>>>>      cursor.execute(sql) #Problem is supposedly here?
            db.commit()
            insert_data()

def insert_data():
    with sqlite3.connect("ATM.db") as db:
        cursor = db.cursor()
        sql = """insert into ATM(Title, First Name, Surname, Balance) values (Mr., Jeremy, Clarkson, 172.16),
                                                                             (Miss, Suzanne, Perry, 15.62)"""
        cursor.execute(sql, values)
        db.commit()


dbName = "ATM.db"
sql = """ create table ATM
          (CustomerID integer,
          Title text
          First Name text,
          Surname text,
          Balance real,
          CustomerID(CustomerID))"""
create_table(dbName, "ATM", sql)

1 个答案:

答案 0 :(得分:1)

错误在于您的SQL代码,而不是Python。

一些事情:

  1. 您需要以分号结束所有sqlite3命令,否则它只是作为一个命令继续阅读。这导致混淆错误的位置。
  2. 添加分号后,我们发现问题实际上在您的CREATE TABLE命令中。这条线毫无意义:"CustomerID(CustomerID))"。您打算设置PRIMARY KEY吗?

    create table ATM (
      CustomerID integer,
      Title text
      First Name text,
      Surname text,
      Balance real,
      PRIMARY KEY(CustomerID)
    );
    
  3. 顺便说一下,你还有另外一个问题。 这是您的查询:

    insert into ATM(Title, First Name, Surname, Balance) values (Mr., Jeremy, Clarkson, 172.16),
                                                                             (Miss, Suzanne, Perry, 15.62)
    

    问题是你需要用引号括起你的字符串,而不是将它们视为裸字,并希望它们能被正确解释:

        insert into ATM(Title, First Name, Surname, Balance) values ("Mr.", "Jeremy", "Clarkson", 172.16),
                                                                             ("Miss", "Suzanne", "Perry", 15.62);
    

    否则,这是一个无效的查询,因为这些单词会使其格式不正确。