How to correctly insert utf-8 characters into a MySQL table using python

前端 未结 4 775
误落风尘
误落风尘 2021-02-05 16:21

I am extremely confused and puzzled by how I store strings with unusual characters (to someone who is used to dealing with a UK English character set) in them.

Here is m

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-05 17:11

    Did you try, this query set names utf8;

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    
    import MySQLdb
    
    mystring = "Bientôt l'été"
    
    myinsert = [{ "name": mystring.encode("utf-8").strip()[:65535], "id": 1 }]
    
    con = MySQLdb.connect('localhost', 'abc', 'def', 'ghi');
    cur = con.cursor()
    
    cur.execute("set names utf8;")     # <--- add this line,
    
    sql = "INSERT INTO 'MyTable' ( 'my_id', 'my_name' ) VALUES ( %(id)s, %(name)s ) ; "
    cur.executemany( sql, myinsert )
    con.commit()
    if con: con.close()
    

提交回复
热议问题