First, the source code is as follows:
Import pymysql from pymysql.cursors Import DictCursor # create a database connection is equivalent to localhost 127.0.0.1 Conn = pymysql.connect (Host = " 127.0.0.1 " , Port = 3306, = User " the root " , the passwd = " xiaobin1314 " , DB = " interface " , charset = " utf8 " ) # establish a cursor, specify the type of cursor to return to the dictionary CUR = conn.cursor (DictCursor) # operation statement, the first two rows only query SQL = ' the SELECT * from Students limit 2; ' # implementation of sql statement cur.execute (SQL) # get all the results of the query RES = cur.fetchall () # print results Print (RES) # close the cursor cur.close () # close the connection conn.close ()
Second, the implementation problems encountered in the script:
1.pymysql.err.OperationalError: (2003, "Can not connect to MySQL server on '127.0.0.1' ([WinError 10061] Because the target machine actively refused it can not connect).")
The reason: The database name is wrong, or user, passwd, port, IP incorrect
Remedy: Fill database connection information:
2.AttributeError: 'NoneType' object has no attribute 'encoding'
The reason: MySQL encoding can only be utf8, but can not be utf8
Solution: charset = "utf8"
Reference connection: http://baijiahao.baidu.com/s?id=1642463236846856193&wfr=spider&for=pc