Python3 use PyMysql to connect to the mysql database

Source: Internet
Author: User
Python3 using PyMysql to connect to the mysql database python 3.x is completely incompatible with the forward, resulting in a library that can be used normally in python2.x, which won't 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 ")

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.