數(shù)據(jù)庫查詢操作在python的數(shù)據(jù)庫
提問人:楊紫紅發(fā)布時間:2020-11-24
以查詢EMPLOYEE表中salary(工資)字段大于1000的所有數(shù)據(jù)為例:
代碼如下:
#!/usr/bin/python
# encoding: utf-8
import MySQLdb
# 打開數(shù)據(jù)庫連接
db = MySQLdb.connect("localhost","root","361way","test" )
# 使用cursor()方法獲取操作游標
cursor = db.cursor()
# SQL 查詢語句
sql = "SELECT * FROM EMPLOYEE \
WHERE INCOME > '%d'" % (1000)
代碼如下:
#!/usr/bin/python
# encoding: utf-8
import MySQLdb
# 打開數(shù)據(jù)庫連接
db = MySQLdb.connect("localhost","root","361way","test" )
# 使用cursor()方法獲取操作游標
cursor = db.cursor()
# SQL 查詢語句
sql = "SELECT * FROM EMPLOYEE \
WHERE INCOME > '%d'" % (1000)
try:
# 執(zhí)行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"
# 關閉數(shù)據(jù)庫連接
db.close()
以上腳本執(zhí)行結果如下:
fname=Mac, lname=Mohan, age=20, sex=M, income=2000
繼續(xù)查找其他問題的答案?
相關視頻回答
點擊加載更多評論>>