查询一行数据
from pymysql import *
def main():
# 创建connect 连接
conn = connect(host='localhost', port=3306, user='root',password='', database='jingdong',charset='utf8')
# 获得cursor 对象
cs1 = conn.cursor()
# 执行 select 语句,并返回受影响的行数:查询一条语句
count = cs1.execute('select * from goods where id >= 4')
# 打印受影响的行数
print('查询到 %d 条数据:' % count)
# 打印数据
for i in range(count):
# 获取查询结果
result = cs1.fetchone()
# 打印查询结果
print(result)
# 关闭 cursor 对象
cs1.close()
conn.close()
if __name__ == '__main__':
main()
查询多行
fetchmany(5) # 查询5行
from pymysql import *
def main():
# 创建connect 连接
conn = connect(host='localhost', port=3306, user='root', database='jingdong')
# 获得cursor 对象
cs1 = conn.cursor()
# 执行 select 语句,并返回受影响的行数:查询一条语句
count = cs1.execute('select * from goods where id >= 4')
# 打印受影响的行数
print('查询到 %d 条数据:' % count)
# 获取查询结果
result = cs1.fetchmany(3)
# 打印查询结果
print(result)
# 关闭 cursor 对象
cs1.close()
conn.close()
if __name__ == '__main__':
main()
总结:
fetchone 查询的是一条记录,循环查询结果,可以得到每个字段
fetchmany 查询的是多条记录,返回结果是元组,循环查询结果,可以得到每条记录。
下面做个小程序:用户可以做出不同选择,1 查询 所有的商品 2查询所有的商品分类 3查询所有的品牌分类
from pymysql import connect
class JD(object):
def __init__(self):
# 创建连接
self.conn = connect(host='localhost', port=3306, user='root', database='jingdong', charset='utf8')
# 获得cursor 对象
self.cursor = self.conn.cursor()
def __del__(self):
# 关闭cursor 对象
self.cursor.close()
self.conn.close()
def show_all_goods(self):
'''显示所有的商品'''
sql = 'select * from goods'
self.cursor.execute(sql)
for temp in self.cursor.fetchall():
print(temp)
def show_good_cates(self):
'''显示所有商品分类'''
sql = 'select name from good_cates'
self.cursor.execute(sql)
for temp in self.cursor.fetchall():
print(temp)
def show_brand_cates(self):
'''显示所有商品品牌分类'''
sql = 'select name from goods_brands'
self.cursor.execute(sql)
for temp in self.cursor.fetchall():
print(temp)
@staticmethod
def show_menus():
print('------京东商城------')
print('1: 查询所有商品')
print('2: 查询所有商品分类')
print('3: 查询所有的商品品牌分类')
return input('请输入您所要执行的功能对应的序号:')
def run(self):
while True:
num = self.show_menus()
if num == '1':
self.show_all_goods()
elif num == '2':
self.show_good_cates()
elif num == '3':
self.show_brand_cates()
else:
print('输入有误,请重新输入:')
def main():
# 创建一个京东对象
jd = JD()
# 调用这个对象的run方法,让其运行
jd.run()
if __name__ == '__main__':
main()