怎么在Python中使用fetchone()查询mysql数据库

发布时间:2021-05-11 15:49:55 作者:Leah
来源:亿速云 阅读:277

这篇文章给大家介绍怎么在Python中使用fetchone()查询mysql数据库,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

python主要应用领域有哪些

1、云计算,典型应用OpenStack。2、WEB前端开发,众多大型网站均为Python开发。3.人工智能应用,基于大数据分析和深度学习而发展出来的人工智能本质上已经无法离开python。4、系统运维工程项目,自动化运维的标配就是python+Django/flask。5、金融理财分析,量化交易,金融分析。6、大数据分析。

demo.py(查询,取出一条数据,fetchone):

from pymysql import *
def main():
  # 创建Connection连接
  conn = connect(host='localhost',port=3306,user='root',password='mysql',database='jing_dong',charset='utf8')
  # 获得Cursor对象
  cs1 = conn.cursor()
  # 执行select语句,并返回受影响的行数:查询一条数据
  count = cs1.execute('select id,name from goods where id>=4')
  # 打印受影响的行数
  print("查询到%d条数据:" % count)
  for i in range(count):
    # 获取查询的结果
    result = cs1.fetchone()
    # 打印查询的结果
    print(result) # 元组 (1, '张三', 20, '男')
    # 获取查询的结果
  # 关闭Cursor对象
  cs1.close()
  conn.close()
if __name__ == '__main__':
  main()

demo.py(查询,取出多条数据,fetchmany,fetchall):

from pymysql import *
def main():
  # 创建Connection连接
  conn = connect(host='localhost',port=3306,user='root',password='mysql',database='jing_dong',charset='utf8')
  # 获得Cursor对象
  cs1 = conn.cursor()
  # 执行select语句,并返回受影响的行数:查询一条数据
  count = cs1.execute('select id,name from goods where id>=4')
  # 打印受影响的行数
  print("查询到%d条数据:" % count)
  # for i in range(count):
  #   # 获取查询的结果
  #   result = cs1.fetchone()  # 取出一条记录,返回元组。
  #   # 打印查询的结果
  #   print(result)
  #   # 获取查询的结果
  # 获取所有记录
  result = cs1.fetchall() # fetchmany(3) 取出3条记录,返回二维元组。
  print(result)  # 二维元组
  # 关闭Cursor对象
  cs1.close()
  conn.close()
if __name__ == '__main__':
  main()

关于怎么在Python中使用fetchone()查询mysql数据库就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. Python制作字符雨(代码)
  2. Python中如何用shutil函数对文件和目录进行操作

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python mysql

上一篇:selenium如何 在python中使用

下一篇:怎么在Python中使用运算符

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》