Python and Hebrew encoding / decoding error

I have a sqlite database that I would like to insert Hebrew values ​​in

I keep getting the following error:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xd7 in position 0: ordinal
not in range(128)

my code is as follows:

runql (u'INSERT to personal values ​​(% (ID) d,% (name) s) '% {' ID ': 1,' name ': fabricate_hebrew_name ()})

    def fabricate_hebrew_name():
        hebrew_names = [u'ירדן',u'יפה',u'תמי',u'ענת',u'רבקה',u'טלי',u'גינה',u'דנה',u'ימית',u'אלונה',u'אילן',u'אדם',u'חווה']
        return random.sample(names,1)[0].encode('utf-8')

Note: runsqlexecuting a query in sqlite fabricate_hebrew_name()should return a string that can be used in my SQL query. any help is much appreciated.

+3
source share
2 answers

Unicode. , , Unicode.

fabricate_hebrew_name Unicode - UTF-8, .

, encode ('utf-8') , .

- runql . Unicode, . , ASCII, , ASCII. UTF-8, - , .

- . , , , %, . SQL-.

# -*- coding: utf-8 -*-
import sqlite3

# create db in memory
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute("CREATE TABLE personal ("
            "id INTEGER PRIMARY KEY,"
            "name VARCHAR(42) NOT NULL)")

# insert random name
import random
fabricate_hebrew_name = lambda: random.choice([
    u'ירדן',u'יפה',u'תמי',u'ענת', u'רבקה',u'טלי',u'גינה',u'דנה',u'ימית',
    u'אלונה',u'אילן',u'אדם',u'חווה'])

cur.execute("INSERT INTO personal VALUES("
            "NULL, :name)", dict(name=fabricate_hebrew_name()))
conn.commit()

id, name = cur.execute("SELECT * FROM personal").fetchone()
print id, name
# -> 1 אלונה
+4

, .

+2

Source: https://habr.com/ru/post/1745313/


All Articles