数据库在 Python 中的读取操作
任何数据库中的 READ 操作是指从数据库中提取一些有用的信息。
建立数据库连接后,即可查询该数据库。既可以使用 fetchone() 方法提取单条记录,也可以使用 fetchall() 方法从数据库表中提取多值。
- fetchone() - 提取查询结果集的下一行。结果集是在使用光标对象查询表时返回的对象。
- fetchall() - 提取结果集中所有的行。如果已经从结果集中提取了一些行,那么它将从结果集中提取剩余的行。
- rowcount - 这是一个只读属性,返回受 execute() 方法影响的行数。
示例
以下过程查询所有工资超过 1000 的EMPLOYEE 表记录 -
#!/usr/bin/python
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
sql = "SELECT * FROM EMPLOYEE \
WHERE INCOME > '%d'" % (1000)
try:
# Execute the SQL command
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
# Now print fetched result
print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \ (fname, lname, age, sex, income )
except:
print "Error: unable to fecth data"
# disconnect from server
db.close()输出
将产生以下结果 -
fname=Mac, lname=Mohan, age=20, sex=M, income=2000
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP