查询一条数据
Python查询Mysql使用 fetchone()方法获取单条数据, 使用fetchall()方法获取多条数据。
fetchone(): 该方法获取下一个查询结果集。结果集是一个对象
fetchall(): 接收全部的返回结果行
rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数。
#coding=utf-8
import pymysql
#创建数据库连接
'''
注:port参数传入的必须是数值类型
self.host_info = "socket %s:%d" % (self.host, self.port)
TypeError: %d format: a number is required, not str
'''
con=pymysql.connect(host='localhost',user='root',password='hdc@328216',database='my_test2',port=3306)
#创建游标对象
cur=con.cursor()
sql='select * from t_student where sage = 28'
try:
cur.execute(sql)
#fetchone()获取一条查询结果保存至元组
result=cur.fetchone()
print('查询数据成功')
print(result)
except Exception as e:
print(e)
print('查询数据失败')
#回滚事务
con.rollback()
finally:
cur.close()
con.close()
结果:
查询数据成功
(1, 'hdc', 28, 90.99)
查询所有数据
#coding=utf-8
import pymysql
#创建数据库连接
con=pymysql.connect(host='localhost',user='root',password='hdc@328216',database='my_test2',port=3306)
#创建游标对象
cur=con.cursor()
sql='select * from t_student where sage = 28'
try:
cur.execute(sql)
#fetchall()获取所有查询结果保存至列表
result=cur.fetchall()
print('查询数据成功')
for student in result:
print(student)
except Exception as e:
print(e)
print('查询数据失败')
#回滚事务
con.rollback()
finally:
cur.close()
con.close()
结果:
查询数据成功
(1, 'hdc', 28, 90.99)
(4, 'vince', 28, 100.0)
查询结果转换为字典类型:
#coding=utf-8
import pymysql
#定义mysql的连接
con=pymysql.connect(host="localhost",user="root",password="hdc@328216",database="my_test2",port=3306)
#创建mysql游标用于执行sql,cursor=pymysql.cursors.DictCursor用来指定执行sql后返回的结果为字典类型
cursor=con.cursor(cursor=pymysql.cursors.DictCursor)
sql="select * from t_student where sage=28"
try:
cursor.execute(sql)
result=cursor.fetchall() #获取所有结果
print(result)
except Exception as e:
print("执行sql异常:",e)
finally:
cursor.close()
con.close()
[{'sname': 'vince', 'sage': 28, 'sid': 4, 'source': 100.0}]