2017-09-30 1 views
0

sqlite에 데이터 프레임을 삽입하려고합니다. 다음과 같이 기존 dataframe은 다음과 같습니다sqlite3에 데이터 프레임을 추가 할 수 없습니다.

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

내 파이썬 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

indexreserved keyword입니다. 키워드 문서에서

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

:이 식별자가 될 수 있도록 당신은 인용을 필요

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.

GUI를 클라이언트는 전형적으로로 SQL을 생성 할 때 당신을 위해 식별자를 인용 처리한다 테이블을 만듭니다. 당신이 발견 한 것처럼

관련 문제