recently helped the buddy to do a program that grabbed the stock information from the web page and saved the corresponding information into the MySQL.

use environment:

Python 2.5, #ffff00, and there are some strange faults in writing program.

is the first problem: insert

Chinese is due to the failure of the character encoding issues. When MySQL is installed, I have set it to utf8 encoding, and the table is also built using utf8 encoding. As long as the program at the beginning #-*- coding: UTF-8 written -*-, and set the connection string when written clear utf8 can use conn=MySQLdb.connect (host= "127.0.0.1 user=", "webdb", "passwd= web123 db=", "Web", "charset= utf8"). When the is set, the Chinese saved in the utf8 encoded from the MySQL will not have a random code.

for Chinese string, such as: a = Pudong Development Bank, before inserting operation, do code conversion a = a.decode ("UTF-8").Encode ("UTF-8") . Then there is no problem with the insertion operation.

second problem: after inserting, you can't save the data just inserted in MySQL.

can be inserted correctly through checking data, but it will not be saved in the table after disconnection. After inspection, it was found that it was conn.commit (). You need to submit an operation after the statement is executed. The source code of the

is as follows.

 coding: UTF-8 #-*- -*- import sys, MySQLdb conn=MySQLdb.connect ("127.0.0.1 host= user=", "webdb", "passwd= web123 db=", "Web", "charset= utf8") to set the charset UTF-8 # cursor=conn.cursor (#) generated # connection pointer object string encoding conversion and insert a = "Shanghai Pudong Development Bank" a = a.decode ("UTF-8").Encode ("UTF-8") # encoding into UTF-8 sql= insert into stocklist (stockno, stockname) values (%s,%s) "# param= generates SQL statements ('600000', a) # generate SQL parameter n = cursor.execute (SQL, param) # the implementation of the above SQL statement # operation is equivalent to n = cursor.execute (" insert into stocklist (stockno, stockname) values ('430004', '"+" Shanghai Pudong Development Bank ".Decode (" UTF-8 ").Encode (" UTF-8 ") +"') ") print n (conn.commit) # submit operation results # query operation Just check the execution of insert operation results of n = cursor.execute ("select * from stocklist row in cursor.fetchall (for)): Print (cursor.close) row[0] + row[1] (conn.close) # # close pointer closes the connection 

summarized above is Xiaobian to introduce the Python MySQLdb the use of UTF-8 encoding into Chinese data, I hope to help you, if you have any questions please give me a message, Xiao Bian will reply you timely. Thank you for your support for the home website of the script!

This paper fixed link:http://www.script-home.com/python-mysqldb-inserts-chinese-data-problems-with-utf-8-encoding.html | Script Home | +Copy Link

Article reprint please specify:Python MySQLdb inserts Chinese data problems with UTF-8 encoding | Script Home

You may also be interested in these articles!