分享

pymysql库的基本使用

 rcylbx 2018-11-23

首先需要安装好MySQL数据库,并建立一个“mypysql”数据库,下面就可以对数据库进行操作了。

示例代码如下:

  1. # --coding:utf-8-- #
  2. import pymysql
  3. # 1.连接名字为"pymysql"的数据库
  4. conn = pymysql.connect(host="localhost", user="root", password="mysqlroot", database="pymysql", port=3306)
  5. cursor = conn.cursor()
  6. # 2.创建表
  7. # sql = """create table students(
  8. # name text,
  9. # username text,
  10. # id int
  11. # )"""
  12. # cursor.execute(sql)
  13. # 3.写入数据:方法一
  14. # sql = """insert into students
  15. # (name, username, id)
  16. # values
  17. # ('黄继光', 'Jason', 123456)"""
  18. # cursor.execute(sql)
  19. # conn.commit()
  20. # cursor.close()
  21. # conn.close()
  22. # 4.写入数据:方法二
  23. # name_ = "李军"
  24. # username_ = "lijun"
  25. # id_num = 1258
  26. # sql = """insert into students
  27. # (name, username, id)
  28. # values
  29. # (%s, %s, %s)"""
  30. # cursor.execute(sql, (name_, username_, id_num))
  31. # # cursor.execute(sql, (name_, username_))
  32. # conn.commit()
  33. # cursor.close()
  34. # conn.close()
  35. # 5.查找数据:cursor.fetchone() 查找1条数据
  36. # 5.1 """select name, username, id from students where id>1"""
  37. # sql = """select name from students where id>1"""
  38. # 5.2 """select * from students where id>1"""
  39. # sql = """select * from students where id>1"""
  40. # cursor.execute(sql)
  41. # while True:
  42. # # cursor.fetchone() 查找1条数据
  43. # result = cursor.fetchone()
  44. # if result:
  45. # print result
  46. # else:
  47. # break
  48. # conn.close()
  49. # 6.查找数据:cursor.fetchmany() 查找1条数据
  50. # """select * from students where id>1"""
  51. # sql = """select * from students where id>1"""
  52. # cursor.execute(sql)
  53. # # cursor.fetchmany(2) 查找2条数据
  54. # result = cursor.fetchmany(2)
  55. # for re in result:
  56. # print re
  57. # conn.close()
  58. # 7.查找数据:cursor.fetchall() 查找1条数据
  59. # """select * from students where id>1"""
  60. # sql = """select * from students where id>1"""
  61. # cursor.execute(sql)
  62. # # cursor.fetchall() 查找2条数据
  63. # result = cursor.fetchall()
  64. # for re in result:
  65. # print re
  66. # conn.close()
  67. # 8.删除和更新数据:
  68. # sql = """delete from students where id=1258"""
  69. # cursor.execute(sql)
  70. # # 插入,删除,更新数据都需要commit()
  71. # conn.commit()
  72. # conn.close()
  73. # 9.更新数据:cursor.fetchall() 查找1条数据
  74. # """select * from students where id>1"""
  75. sql = """update students set username=(%s) where id=124"""
  76. cursor.execute(sql, ("leiweijia"))
  77. conn.commit()
  78. conn.close()

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多