python3 connects to the mysql database instance using PyMysql

  • 2020-05-26 09:22:50
  • OfStack

The 3.x of python language is completely incompatible, resulting in libraries that we can use normally in python2.x, but can't use in python3, such as mysqldb
Currently, MySQLdb does not support python3.x, Python3.x connecting MySQL schemes: oursql, PyMySQL, myconnpy, etc.

Here's how to install and use pymysql for python3, and I'll talk about the other two later.

1. pymysql installation

pymysql is a substitute for mysqldb in the python3 environment. It enters the command line and installs pymysql using pip


pip install pymysql3

2. pymysql use

If you want to use mysqldb, just add the following two lines of code to the beginning of the py file.


# The introduction of pymysql
import pymysql 
# As a mysqldb1 Of course, do not write this sentence, then follow pymysql The way of 
pymysql.install_as_MySQLdb()

3. Sample pymysql query


__author__ = 'pythontab.com'
# The import pymysql The package 
import pymysql
try:
  # To obtain 1 Two database connections, note if yes UTF-8 Type, need to make database 
  conn=pymysql.connect(host='localhost',user='pythontab',passwd='pythontab',db='pythontab',port=3306,charset='utf8')
  cur=conn.cursor()# To obtain 1 A cursor 
  cur.execute('select * from user')
  data=cur.fetchall()
  for d in data :
    # Pay attention to int Types need to be used 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 resources 
except Exception :print(" The query fails ")


Related articles: