简体   繁体   中英

How to insert unicode string in Database using Pyodbc with python2.7

Below is my sample code:

import pyodbc
conn = pyodbc.connect(driver = '{SQL Server}', \
                   server = 'localhost', \
                   uid = 'sa', \
                   pwd = '1234', \
                   autocommit = True, trusted_connection='yes', database = 'DB')                       
Objcursor = conn.cursor()
mystring1 = "MÜNRÜC"
mystring = mystring1.decode("utf-8",'replace')
sql = "INSERT INTO system (name) VALUES ('%s')" %(mystring)
Objcursor.execute(sql)
conn.Commit()

When I run this code snippet, I get output as "M?N?R?C" since I have used replace while encoding. if I do not use replace it gives an error doesn't encode the string. can someone please help on how to insert the unicode string using pyodbc in database without replacing the character/data loss.

Firstly, you may be constrained by other factors but it would be a good idea to stop using python 2.7 since it is now unsupported.

Secondly, you don't seem to have declared the encoding of your source file so mystring1 = "MÜNRÜC" probably isn't doing what you think it is.

Solution:

You should explicitly declare the encoding of your source file and it is probably sensible to only use unicode objects (not python 2.7 strings). You can do this explicitly like so:

# -*- coding: utf-8 -*-
import pyodbc
conn = pyodbc.connect(driver = '{SQL Server}', \
                   server = 'localhost', \
                   uid = 'sa', \
                   pwd = '1234', \
                   autocommit = True, trusted_connection='yes', database = 'DB')            

objcursor = conn.cursor()  # lowercase names
name_unicode = u"MÜNRÜC"  # descriptive variable name
sql = u"INSERT INTO system (name) VALUES ('%s')" % name_unicode  # unicode objects
objcursor.execute(sql)
conn.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