Home  >  Article  >  Backend Development  >  How to perform python database query? (Example analysis)

How to perform python database query? (Example analysis)

乌拉乌拉~
乌拉乌拉~Original
2018-08-22 17:14:267381browse

In this article, let’s learn about the relevant knowledge about python database. Some friends may have just come into contact with the python programming language and do not have a special understanding of this aspect. Next, This article will introduce you to the relevant knowledge about data in python query database.

Query operation of database

Python queries Mysql using the fetchone() method to obtain a single piece of data, and the fetchall() method to obtain multiple pieces of 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 rows affected by executing the execute() method. number.

Example demonstration

Query all data in the EMPLOYEE table whose salary field is greater than 1000:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import MySQLdb

# 打开数据库连接
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )

# 使用cursor()方法获取操作游标 
cursor = db.cursor()

# SQL 查询语句
sql = "SELECT * FROM EMPLOYEE \
       WHERE INCOME > '%d'" % (1000)
try:
   # 执行SQL语句
   cursor.execute(sql)
   # 获取所有记录列表
   results = cursor.fetchall()
   for row in results:
      fname = row[0]
      lname = row[1]
      age = row[2]
      sex = row[3]
      income = row[4]
      # 打印结果
      print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
             (fname, lname, age, sex, income )
             
except:
   print "Error: unable to fecth data"
   
# 关闭数据库连接
db.close()

The execution results of the above script are as follows:

fname=Mac, lname=Mohan, age=20, sex=M, income=2000

The above is all the content described in this article. This article mainly introduces the relevant knowledge of python database query operation. I hope you can use the information to understand the above content. I hope what I have described in this article will be helpful to you and make it easier for you to learn python.

For more related knowledge, please visit the Python tutorial column on the php Chinese website.

The above is the detailed content of How to perform python database query? (Example analysis). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn