python讀取檔案寫入資料庫中編碼問題

2021-07-22 04:35:55 字數 1772 閱讀 1185

在把sina資料儲存到資料庫的過程中又碰到了些新問題。

文字如下:

# coding=utf-8

import mysqldb

import codecs

#讀取爬取到的檔案,按照使用者名稱判斷是否在資料庫中存在,並返回id

infofile = codecs.open("inforead.txt", 'r', 'utf-8')

infofilenew = codecs.open("infowrite.txt", 'a', 'utf-8')

username = infofile.readline()

conn = mysqldb.connect (host = "localhost", user = "root", passwd = "123456", db = "school", use_unicode=true, charset="utf8")

cursor = conn.cursor ()

# cursor.execute('set names gbk')

while username!="":

username = username.split(' ')

givenname = username[0]

givenname = givenname.encode("utf8")

#判斷該使用者是否已存在

cursor.execute ("select id from teacher where name='"+givenname+"'")

rows = cursor.fetchall()

if len(rows)>0:

#存在則返回該使用者的id

id = rows[0][0]

elif len(rows)==0:

#不存在則插入到資料庫

# print type(givenname)

# print givenname

# print type(givenname)

# print givenname

print givenname=='流'

cursor.execute("insert into teacher(name,age,xi) values('"+givenname+"',12,6)")

conn.commit()

cursor.execute ("select id from teacher where name='"+givenname+"'")

row = cursor.fetchall()

id = row[0][0]

print id

infofilenew.write(str(id)+" "+username[1])

username = infofile.readline()

cursor.close ()

conn.close ()

現在來看,整個檔案有多處提到編碼問題:

首先在開啟檔案載入到記憶體過程中開啟方式是utf8,也就是說檔案處理是utf8.

其次,在mysql的connection處提到寫入資料庫的格式為utf8。問題就出在這,因為之前測試過程中試著在寫入資料庫之前將資料庫的一些編碼格式改為gbk,才寫了這個set。。。但是,這就與utf8產生了衝突。導致我的givenname編碼產生衝突,成了gbk,所以我還需要將givenname格式encode為utf8.。。

問題大概都明白了,對於字元編碼理解又多了些。

python寫入與讀取資料庫

前面記錄了python基礎,記錄了爬蟲,記錄了資料視覺化,記錄了機器學習,下面將了解python web,博主看資料學習了2天才看懂了如何通過python讀寫資料庫 import mysql.connector,pymysql from flask import flask from flask s...

PHP讀取EXCEL檔案寫入資料庫

php讀取ecel檔案寫入資料庫功能的實現使用到了phpexcel類庫。完整 如下 uploadfile upload files basename files userfile name message if move uploaded file files userfile tmp name u...

PHP讀取TXT檔案寫入資料庫

php讀取txt檔案寫入資料庫完整 如下 包括檔案型別 大小 欄位為空的判斷,以及事務的處理 uploadfile upload files basename files userfile name message 判斷上傳檔案格式 string txt extend pathinfo files ...