位置:首頁(yè) > 軟件操作教程 > 編程開(kāi)發(fā) > Python > 問(wèn)題詳情

數(shù)據(jù)庫(kù)查詢操作在python的數(shù)據(jù)庫(kù)

提問(wèn)人:楊紫紅發(fā)布時(shí)間:2020-11-24
以查詢EMPLOYEE表中salary(工資)字段大于1000的所有數(shù)據(jù)為例:
  代碼如下:
#!/usr/bin/python
# encoding: utf-8
import MySQLdb
# 打開(kāi)數(shù)據(jù)庫(kù)連接
db = MySQLdb.connect("localhost","root","361way","test" )
# 使用cursor()方法獲取操作游標(biāo)
cursor = db.cursor()
# SQL 查詢語(yǔ)句
sql = "SELECT * FROM EMPLOYEE \
       WHERE INCOME > '%d'" % (1000)

try:

 # 執(zhí)行SQL語(yǔ)句
   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]
      # 打印結(jié)果
      print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
             (fname, lname, age, sex, income )
except:
   print "Error: unable to fecth data"
# 關(guān)閉數(shù)據(jù)庫(kù)連接
db.close()

以上腳本執(zhí)行結(jié)果如下:
fname=Mac, lname=Mohan, age=20, sex=M, income=2000

image.png

繼續(xù)查找其他問(wèn)題的答案?

相關(guān)視頻回答
回復(fù)(0)
返回頂部