打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
pymysql库的基本使用

首先需要安装好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()
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Python连接MySQL数据库之pymysql模块使用
【Python之路】第十九篇
建议收藏!Python 读取千万级数据自动写入 MySQL 数据库
Python爬虫之数据存储篇
mysql之pymsql的使用
在Python中使用MySQL--PyMySQL的基本使用
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服