2017-09-30 2 views
0

sqliteにデータフレームを挿入しようとしています。次のように私の既存のデータフレームは、次のとおりです。sqlite3にdataframeを追加できません

--------------------------------------- 
    |date  |location|location_code| 
--------------------------------------- 
0 |12/14/2016 | FL  | 2 
1 |12/15/2016 | NY  | 3 

私のpython 3コード:

import sqlite3 

conn = sqlite3.connect('transaction.sqlite') 
cur = conn.cursor() 

cur.executescript(''' 
    DROP TABLE IF EXISTS New; 

    CREATE TABLE New (
     index INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, 
     date TEXT, 
     location TEXT, 
     location_code INTEGER) 
''') 

df.to_sql("Records", conn, if_exists="append") 

conn.commit() 
conn.close() 

私は、コードを実行すると、私は次のエラーを取得する:

Traceback (most recent call last): 
    File "C:/dbtest.py", line 15, in <module> 
    ''') 
sqlite3.OperationalError: near "index": syntax error 

私はその時、私を知っています単語のインデックスを別の単語に変更すると、動作します。

しかし、私はDBブラウザでsqliteのindexというフィールドを作成しても問題ありません。

答えて

1

あなたが気づいてきたように、indexが予約語に、あなたがあるとして、少なくともではない、列名のためにそれを使用することはできません - あなたは、二重引用符(")を使用して、それをエスケープする必要があると思います。

cur.executescript(''' 
    DROP TABLE IF EXISTS New; 

    CREATE TABLE New (
     "index" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, 
     date TEXT, 
     location TEXT, 
     location_code INTEGER) 
''') 

おそらく、DBブラウザは名前を自動的にエスケープし、そこで作成した列を予約語で呼び出すことができます。

0

indexは、reserved keywordです。キーワードのドキュメントから

CREATE TABLE New (
    "index" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, 
    date  TEXT, 
    location TEXT, 
    location_code INTEGER) 

:それは識別子であるためにあなたが引用にそれを必要とする、それがSQLを生成するときにA GUIクライアントは一般的にあなたのための識別子を引用するの面倒を

If you want to use a keyword as a name, you need to quote it. There are four ways of quoting keywords in SQLite:

'keyword'
A keyword in single quotes is a string literal.

"keyword"
A keyword in double-quotes is an identifier.

[keyword]
A keyword enclosed in square brackets is an identifier. This is not standard SQL. This quoting mechanism is used by MS Access and SQL Server and is included in SQLite for compatibility.

`keyword`
A keyword enclosed in grave accents (ASCII code 96) is an identifier. This is not standard SQL. This quoting mechanism is used by MySQL and is included in SQLite for compatibility.

テーブルを作成します。

関連する問題