经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库运维 » MySQL » 查看文章
PyMySQL模块的使用
来源:cnblogs  作者:Wualin  时间:2018/11/7 0:56:05  对本文有异议

安装:

  1. pip3 install pymysql

基本使用

  1. import pymysql
  2. # 建立连接
  3. conn = pymysql.connect(
  4. host='127.0.0.1',
  5. port=3306,
  6. user='root',
  7. password='123456',
  8. db='db5',
  9. charset='utf8'
  10. )
  11. user = input('user >>>')
  12. pwd = input('pwd >>>')
  13. # 拿到游标
  14. cursor = conn.cursor()
  15. # 执行sql语句
  16. sql = 'select * from userinfo where user=%s and password=%s'
  17. rows = cursor.execute(sql,(user,pwd))#解决mysql注入问题
  18. # 关闭连接
  19. cursor.close()
  20. conn.close()
  21. if rows:
  22. print('111')
  23. else:
  24. print(rows)

pymysql增删该查

  • 增删改
  1. import pymysql
  2. # 建立连接
  3. conn = pymysql.connect(
  4. host='127.0.0.1',
  5. port=3306,
  6. user='root',
  7. password='123456',
  8. db='db5',
  9. charset='utf8'
  10. )
  11. # 拿到游标
  12. cursor = conn.cursor()
  13. # 执行sql语句
  14. #增删改,只需要将insert更换成对应语句即可
  15. sql = 'insert into userinfo(user,password) values (%s,%s)'
  16. # rows = cursor.execute(sql,('miao',321))#解决mysql注入问题
  17. rows = cursor.executemany(sql,[('wxx',123),('mxx',1234)]) # 插入多行
  18. print(cursor.lastrowid)#查看之前游标走到哪里了
  19. conn.commit()# 提交
  20. # 关闭连接
  21. cursor.close()
  22. conn.close()
  23. if rows:
  24. print('111')
  25. else:
  26. print(rows)
  • 查询
  1. import pymysql
  2. conn = pymysql.connect(
  3. host='127.0.0.1',
  4. port=3306,
  5. user='root',
  6. password='123456',
  7. db='db5',
  8. charset='utf8'
  9. )
  10. cursor = conn.cursor(pymysql.cursors.DictCursor)# 以字典形式返回查询结果,调用cursor.fetchon打印出来的结果以字典形式打印
  11. # 查询
  12. rows = cursor.execute('select * from userinfo;')
  13. print(cursor.fetchone())# 打印一行
  14. print(cursor.fetchall())# 打印全部
  15. # print(cursor.fetchmany())# 指定查询个数
  16. cursor.scroll(3,mode='relative')# 相对当前位置移动
  17. cursor.scroll(2,mode='abssolute')# 相对绝对位置移动
  18. cursor.close()
  19. conn.close()
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号