2017-05-20 11 views
0

これは私のプログラムです。構文エラーわからないのですか? python3

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) 

これは私が取得しています構文エラーメッセージです:構文エラーがあるが、私は、文字通り、問題が何であるか見当がつかない場所を正確にそれは私に語りました。コードに矢印を付けて強調表示しています。

line 23, in create_table 
    cursor.execute(sql) 
sqlite3.OperationalError: near "(": syntax error 

答えて

1

エラーはPythonではなくSQLコード内にあります。

いくつかのこと:

  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) 
    ); 
    

、あなたは別の問題を抱えています。 これはあなたのクエリです:

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); 

そうでない場合それは、裸の単語が不正な形式にするため、無効なクエリです。

+0

私はまだ同じ構文エラーが発生しています。私はそのクエリで間違いを認識し、既に変更しました!私は全体の挿入データ関数を削除してもそれをテストしたが、cursor.execute(sql)を指す同じ構文エラーがあります sqlite3.OperationalError:near( ":"構文エラー: –

+1

編集して固定しました –

+0

助けてくれてありがとう!素敵な一日を! –

関連する問題