LoginSignup
8
9

More than 5 years have passed since last update.

pythonのsqlite3 に日本語(マルチバイト文字列)を格納する

Last updated at Posted at 2013-06-25

"文字列はunicode にしてからsqlite3モジュールに渡す" ようにすると
問題なくマルチバイト文字列に対応できる。

import sqlite3,sys,os

con = sqlite3.connect("./temp.sqlite")

#テーブル作成
sql = u"""
  create table filepath(
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    path text);"""
con.execute(sql)

#標準入力からファイルリストを受け取り
#DBに格納する
for rwln in iter(sys.stdin.readline,""):
  path = rwln.rstrip('\n') #末尾改行を削除
  sql = u"""insert into filepath(path) values (?); """
  cur = self.con.cursor()
  #ファイルシステムのエンコーディングはsys.getfilesystemencoding() で取得できるので
  #これを使ってunicode()関数で変換後にsqliteモジュールに渡す
  cur.execute(sql,(unicode(path, sys.getfilesystemencoding()),))

この方法以外にもbase64変換後に格納する事もできるけど、
エンコーディングが特定出来る場合はunicodeにしとくのが良い。

8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9