Python 3x is completely incompatible with the forward, resulting in a library that can be used normally in python2x, which cannot be used in python3. for example, mysqldb currently does not support python 3 python 3. x is completely backward compatible. as a result, the database that we can use normally in python2.x cannot be used in python3. for example, mysqldb
Currently, MySQLdb does not support python3.x and Python3.x to connect to MySQL.
Next, let's talk about how to install and use pymysql in python3. I will talk about the other two solutions later.
1. install pymysql
Pymysql is a substitute for mysqldb in python3 environment. enter the command line and use pip to install pymysql.
pip install pymysql3
2. use pymysql
If you want to use mysqldb, simply add the following two lines of code at the beginning of the py file.
# Introduce pymysqlimport pymysql # if it is used as mysqldb, you can also skip this sentence. then follow the pymysql method: pymysql. install_as_MySQLdb ()
3. pymysql query example
_ Author _ = 'pythontab. com '# import pymysql package import pymysqltry: # get a database connection, note that if it is a UTF-8 type, you need to develop the database conn = pymysql. connect (host = 'localhost', user = 'pythontab', passwd = 'pythontab', db = 'pythontab', port = 3306, charset = 'utf8') cur = conn. cursor () # obtain a cursor cur.exe cute ('select * from user') data = cur. fetchall () for d in data: # note that the int type must use the str function to escape print ("ID:" + str (d [0]) + 'user name: '+ d [1] + "registration time:" + d [2]) cur. close () # close the cursor conn. close () # Release Database Resource failed t Exception: print ("query failed ")
The above is a detailed description of how python3 uses PyMysql to connect to the mysql database. For more information, see other related articles in the first PHP community!