1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| """ 数据库查询操作 Python查询Mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。
fetchone(): 该方法获取下一个查询结果集。结果集是一个对象 fetchall(): 接收全部的返回结果行. rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数。
实例: 查询EMPLOYEE表中salary(工资)字段大于1000的所有数据: """
import pymysql
ip = "localhost" user = 'root' pwd = '1234'
db = pymysql.connect(ip, user, pwd, "matt")
cursor = db.cursor()
sql = "SELECT * FROM EMPLOYEE \ WHERE INCOME > %s" % (1000) try: 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=%s,sex=%s,income=%s" % \ (fname, lname, age, sex, income)) except: print("Error: unable to fetch data")
db.close()
|