Search code examples
pythonoracle-databasepython-2.7unicodecx-oracle

Unicode insert of Russian into Oracle DB with Python 2.7


I have a problem unicode russian word. I have python 2.7.

# -*- coding: utf-8 -*-
from __future__ import print_function
import cx_Oracle
import csv
import sys
# sys.setdefaultencoding() does not exist, here!
reload(sys)  # Reload does the trick!
sys.setdefaultencoding('UTF8')
teh2 = ['Col1','Col2']
va = [(108, u"русский")]
for i in va:
    cur.execute("INSERT INTO Mytable("+ teh2[0] + "," + teh2[1] +") VALUES('"+ str(i[0]) + "', '"+ str(i[1]) + "')")
con.commit()
con.close()

result: enter image description here


Solution

  • See Characters Sets and National Language Support (NLS) in the cx_Oracle documentation. You probably want to connect using something like:

    import cx_Oracle
    connection = cx_Oracle.connect(connectString, encoding="UTF-8", nencoding="UTF-8")
    

    The character set of the database also has a role to play, since inserted data will be mapped into that character set.

    Regarding the string concatenation - as noted in a comment, never, ever do this. See the warning and links in SQL Queries.