Python3 uses PyMysql to connect to the mysql database instance, and python3pymysql

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.