Python3 uses PyMysql to connect to the mysql database instance, and python3pymysql
Python 3.x is completely backward compatible, so that we can use a library in python2.x normally. For example, mysqldb cannot be used in python3.
Currently, MySQLdb does not support python3.x and Python3.x to connect to MySQL. the following solutions are available: oursql, PyMySQL, and myconyy.
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 all the content of this article. I hope it will be helpful for your learning and support for helping customers.