當大家寫python insert資料到 資料庫時 有時會出現 'latin-1' code error

簡單來講就是你想insert的資料無法被被編碼

例如:
原本資料insert(產生了剛剛編碼的問題)

def insert_Sentance(ID,Content,date,Type):
    db = pymysql.connect("127.0.0.1","test","test","test")
    cursor = db.cursor()
    cursor.execute("SELECT VERSION()")
    data_db = cursor.fetchone()
    sql = """INSERT INTO table(ID,Sentance,DateTime,NoteType)
    VALUES (%s,%s,%s,%s) """  # %s字串  %d整數十進位
    data = (ID,Content,date,Type)
    cursor.execute(sql, data)  #變數插入
    db.commit() 
    
但現在只要加入charset='utf8', init_command='SET NAMES UTF8'    這行即可解決編碼問題

def insert_Sentance(ID,Content,date,Type):
    db = pymysql.connect("127.0.0.1","test","test","test",charset='utf8', init_command='SET NAMES UTF8')
    cursor = db.cursor()
    cursor.execute("SELECT VERSION()")
    data_db = cursor.fetchone()
    sql = """INSERT INTO table(ID,Sentance,DateTime,NoteType)
    VALUES (%s,%s,%s,%s) """  # %s字串  %d整數十進位
    data = (ID,Content,date,Type)
    cursor.execute(sql, data)  #變數插入
    db.commit() 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 晨柚 的頭像
    晨柚

    晨柚的部落格

    晨柚 發表在 痞客邦 留言(0) 人氣()