[python] sqlite3.ProgrammingError : 8 비트 바이트 열을 해석 할 수있는 text_factory를 사용하지 않는 한 8 비트 바이트 열을 사용해서는 안됩니다.

Python에서 SQLite3를 사용하여 UTF-8 HTML 코드 조각의 압축 된 버전을 저장하려고합니다.

코드는 다음과 같습니다.

...
c = connection.cursor()
c.execute('create table blah (cid integer primary key,html blob)')
...
c.execute('insert or ignore into blah values (?, ?)',(cid, zlib.compress(html)))

어느 시점에서 오류가 발생합니까?

sqlite3.ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings.

‘blob’대신 ‘text’를 사용하고 HTML 스 니펫을 압축하지 않으면 모두 잘 작동합니다 (db는 크지 만). ‘blob’을 사용하고 Python zlib 라이브러리를 통해 압축하면 위의 오류 메시지가 나타납니다. 나는 주위를 둘러 보았지만 이것에 대한 간단한 답을 찾을 수 없었다.



답변

sqlite3에서 유니 코드 문자열 대신 8 비트 문자열을 사용하려면 sqlite 연결을 위해 approptiate text_factory를 설정합니다.

connection = sqlite3.connect(...)
connection.text_factory = str


답변

해결책을 찾았습니다. 검색에 조금 더 시간을 투자 했어야했습니다.

해결책은 다음과 같이 값을 Python ‘버퍼’로 ‘캐스트’하는 것입니다.

c.execute('insert or ignore into blah values (?, ?)',(cid, buffer(zlib.compress(html))))

바라건대 이것은 다른 사람을 도울 것입니다.


답변

BLOB 유형으로 작업하려면 먼저 zlib 압축 문자열을 이진 데이터로 변환해야합니다. 그렇지 않으면 sqlite가이를 텍스트 문자열로 처리하려고합니다. 이것은 sqlite3.Binary ()로 수행됩니다. 예를 들면 :

c.execute('insert or ignore into blah values (?, ?)',(cid,
sqlite3.Binary(zlib.compress(html))))


답변

통사론:

5 가지 유형의 가능한 스토리지 : NULL, INTEGER, TEXT, REAL 및 BLOB

BLOB는 일반적으로 피클 모델 또는 딜 피클 모델을 저장하는 데 사용됩니다.

> cur.execute('''INSERT INTO Tablename(Col1, Col2, Col3, Col4) VALUES(?,?,?,?)''', 
                                      [TextValue, Real_Value, Buffer(model), sqlite3.Binary(model2)])
> conn.commit()

> # Read Data:
> df = pd.read_sql('SELECT * FROM Model, con=conn) 
> model1 = str(df['Col3'].values[0]))
> model2 = str(df['Col'].values[0]))


답변

원시 출력 대신 repr (html)을 사용하여 값을 저장 한 다음 사용할 값을 검색 할 때 eval (html)을 사용할 수 있습니다.

c.execute('insert or ignore into blah values (?, ?)',(1, repr(zlib.compress(html))))


답변