Python3.4 how to connect to mysql pymysql to connect to mysql database, python3.4pymysql

Source: Internet
Author: User
Tags python 2 7

Python3.4 how to connect to mysql pymysql to connect to mysql database, python3.4pymysql
This article describes how to connect Python 3 4 to the mysql database. In Python 3 4, mysqldb of Python 2 7 cannot connect to the mysql database. You can use pymysql.

In python3.4, mysqldb of python2.7 cannot connect to the mysql database. You can use pymysql to connect to mysql.

Procedure:

Serial Number Description
1 go to github to download the pymysql installation package pymysql https://github.com/PyMySQL/PyMySQL
2. decompress the package to a drive letter.
3. Open the cmd window (in Windows) and run the command in the root directory of pymysql. python setup. py install
4. Import pymysql in the program
5. Connect to the database

Database operation API documentation connection: http://legacy.python.org/dev/peps/pep-0249/

Example:
 

Sample Code:
_ Author _ = 'qindongliang'
# Import a pymysql package
Import pymysql
Try:
# Get A database connection, note that if it is a UTF-8 type, you need to develop a database
Conn = pymysql. connect (host = 'localhost', user = 'root', passwd = 'qin', db = 'people', port = 3306, charset = 'utf8 ')
Cur = conn. cursor () # Get a cursor
Cur.exe cute ('select * from person ')
Data = cur. fetchall ()
For d in data:
# Note that the int type must be escaped using the str Function
Print ("ID:" + str (d [0]) + 'name: '+ d [1] + "Gender:" + d [2])
 
Cur. close () # close the cursor
Conn. close () # release database resources
Failed t Exception: print ("Exception occurred ")

Output result:
 

D: \ python \ python.exe D:/pythonide/pythonprojectworkspace/python/mysql. py
ID: 1 Name: Qin Tian Gender: male
ID: 2 Name: Wang Jing Gender: Female
 
Process finished with exit code 0
  • This article is from: Linux technical network
  • Link: http://www.ahlinux.com/python/13641.html

Related Article

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.