Error in using MySQLdb to connect to MySQL database in Python (use PyMySQL to connect to the database instead)

       When using the MySQLdb module in Python to connect to the MySQL database, since this module is no longer supported in Python 3.x, PyMySQL is used instead. Therefore, you need to install PyMySQL first . Just change the link in the article to pip install pymysql. After the installation is complete, you can import the module. The sample program is as follows:

import os, sys
import pymysql
# Connect to the database
try:
    conn = pymysql.connect(host='localhost',user='root',passwd='',db='abook')       
except Exception as e:
    print (e) # print error
    sys.exit()
cursor = conn.cursor()
sql = "insert into address(name, address) values (%s, %s)"
values ​​= (("Zhang Zhang", "Beijing Haidian District"), ("Li Li", "Beijing Haidian District"), ("Wang Wang", "Beijing Haidian District"))
try:
    cursor.executemany(sql, values) # Insert multiple pieces of data
except Exception as e:
    print (e) # print error
sql = "select * from address"
cursor.execute(sql) # Query data
data = cursor.fetchall()
if data:
    for x in data:
        print (x[0], x[1])
cursor.close() # close the cursor
conn.close()

But when running the program, the following problem occurs:

'latin-1' codec can't encode characters in position 2-3:ordinal not in range(256)


Just change conn = pymysql.connect(host='localhost',user='root',passwd='',db='abook') to conn = pymysql.connect(host='localhost',user='root ',passwd='',db='abook', charset='utf8' ).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325899065&siteId=291194637