简体   繁体   中英

Save utf-8 strings into sqlite table with python (sqlite3 module)

I am using python 2.7.6 and sqlite3. Here the part of code which must create the table named goods:

c.execute("""create table goods(
                            Art varchar(12) primary key,
                            Name_G varchar(30),
                            Meas varchar(3),
                            Price_G double unsigned,

                            check (Meas in ('кг.','л.','шт.')))""")

Don't blame me for such method, it's the exercise requirement. THe field Meas can contain only one of three strings. They are listed in constraint and they are in Russian. This query executes succesfully but if I check the data in database I see it stores the following SQL:

CREATE TABLE goods(
                            Art varchar(12) primary key,
                            Name_G varchar(30),
                            Meas varchar(3),
                            Price_G double unsigned,

                            check (Meas in ('кг.','л.','шт.')))

As you can see, it's not Russian. Is there any method to store correct data in the database? encode() method, u'' didn't work for me.

The following instructions work correctly for me:

alex@rhyme ~/tmp $ echo $LANG
ru_RU.UTF-8
alex@rhyme ~/tmp $ python    
Python 2.7.6 (default, Feb  5 2014, 11:50:47) 
[GCC 4.7.2 20121109 (ALT Linux 4.7.2-alt8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite3
>>> db = sqlite3.connect('sample1.db')
>>> c = db.cursor()
>>> c1 = c.execute('PRAGMA encoding="UTF-8";')
>>> c1 = c.execute('CREATE TABLE sample (id INTEGER PRIMARY KEY AUTOINCREMENT, t VARCHAR(3) NOT NULL DEFAULT  "руб");')
>>> c1 = c.execute('INSERT INTO sample DEFAULT VALUES;')
>>> db.commit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM