2022년 10월 8일 토요일

sqlite3 에서 unrecognized token 오류 해결

 

sqlite 에서 insert into 할때 오류가 나는 경우가 있습니다.

debugging을 해보면 예상치 못한 곳에서 발생합니다.


아래 코드를 보시기 바랍니다.

json_dump = json.dumps(value)
print(f"{key}//{json_dump}")
try:
cur.execute(f"INSERT INTO '{self.table_name}' VALUES ('{nowtime}','{key}','{json_dump}')")

json_dump 는 str 형태이고 이것을 VALUES ('{json_dump}') 로 표현할때 해당 str내부에 작은 따옴표(') 가 존재한다면 unrecognized token 오류가 발생합니다.


해결책

https://www.sqlite.org/lang_expr.html#hexint 여기에 설명이 되어 있는데

A string constant is formed by enclosing the string in single quotes ('). A single quote within the string can be encoded by putting two single quotes in a row - as in Pascal.

문자열 상수는 문자열을 작은따옴표(')로 묶어서 형성됩니다. 문자열 내의 작은 따옴표는 Pascal에서와 같이 두 개의 작은 따옴표를 연속으로 넣어 인코딩할 수 있습니다. 


즉 ' => '' 로 변환하는 코드를 추가로 넣어야 합니다.


개선된 코드

json_dump = json.dumps(value)
json_dump = str(json_dump)
json_dump = json_dump.replace("'", "''")
print(f"{key}//{json_dump}")
try:
cur.execute(f"INSERT INTO '{self.table_name}' VALUES ('{nowtime}','{key}','{json_dump}')")


댓글 없음:

댓글 쓰기