How do i make a python database query? (Instance parsing)

Source: Internet
Author: User
In this article, let's take a look at Python databaseof knowledge, some friends may have just come into contact with the programming language of Python, not particularly in this regard, in the next article will bring you to learn about python Query DatabaseKnowledge about the data in the.

Query operations for databases

Python queries MySQL uses the Fetchone () method to get a single piece of data, using the Fetchall () method to get multiple data.

1.fetchone (): This method gets the next query result set. The result set is an object

2.fetchall (): Receives all the returned result rows.

RowCount: This is a read-only property and returns the number of rows affected after the Execute () method is executed.

Example Demo

Query all data with the salary (payroll) field greater than 1000 in the employee table:

#!/usr/bin/python#-*-coding:utf-8-*-import mysqldb# Open database Connection db = MySQLdb.connect ("localhost", "testuser", "test123", " TESTDB ", charset= ' UTF8 ') # using the cursor () method to get the cursor cursor = db.cursor () # SQL query Statement sql =" SELECT * from EMPLOYEE \       WHERE INCO ME > '%d ' "%" try:   # Execute SQL statement   cursor.execute (SQL)   # get all records list   results = Cursor.fetchall ()   For row in results:      fname = row[0]      lname = row[1] Age      = row[2]      sex = row[3]      income = row[4]      # Print Results      print "fname=%s,lname=%s,age=%d,sex=%s,income=%d"% \             (fname, lname, age, sex, income)             except:   print "error:unable to FECTH data"   # Close database connection Db.close ()

The results of the above script execution are as follows:

Fname=mac, Lname=mohan, age=20, Sex=m, income=2000

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.