資料庫在 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

更新於: 31-1 月-2020

665 次瀏覽

助力您的職業生涯

完成課程後獲得認證

開始學習
廣告
© . All rights reserved.