Python3.6简单的操作Mysql数据库的三个实例

yipeiwu_com5年前Python基础

安装pymysql

参考:https://github.com/PyMySQL/PyMySQL/

pip install pymsql

实例一

import pymysql
# 创建连接
# 参数依次对应服务器地址,用户名,密码,数据库
conn = pymysql.connect(host='127.0.0.1', user='root', passwd='123456', db='demo')
# 创建游标
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 执行语句返回影响的行数
effect_row = cursor.execute("select * from course")
print(effect_row)
# 获取所有数据
result = cursor.fetchall()
result = cursor.fetchone() # 获取下一个数据
result = cursor.fetchone() # 获取下一个数据(在上一个的基础之上)
# cursor.scroll(-1, mode='relative') # 相对位置移动
# cursor.scroll(0,mode='absolute') # 绝对位置移动
# 提交,不然无法保存新建或者修改的数据
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()

实例二

import pymysql
# 建立连接
conn = pymysql.connect(host='127.0.0.1', user='root', passwd='123456', db='demo')
# 创建游标
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 插入一条数据 %s是占位符 占位符之间用逗号隔开
effect_row = cursor.execute("insert into course(cou_name,time) values(%s,%s)", ("Engilsh", 100))
print(effect_row)
conn.commit()
cursor.close()
conn.close()

实例三

import pymysql.cursors
# Connect to the database
connection = pymysql.connect(host='localhost',
        user='user',
        password='passwd',
        db='db',
        charset='utf8mb4',
        cursorclass=pymysql.cursors.DictCursor)
try:
 with connection.cursor() as cursor:
  # Create a new record
  sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
  cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
 # connection is not autocommit by default. So you must commit to save
 # your changes.
 connection.commit()
 with connection.cursor() as cursor:
  # Read a single record
  sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
  cursor.execute(sql, ('webmaster@python.org',))
  result = cursor.fetchone()
  print(result)
finally:
 connection.close()

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对【听图阁-专注于Python设计】的支持。如果你想了解更多相关内容请查看下面相关链接

相关文章

在pycharm中python切换解释器失败的解决方法

在pycharm中python切换解释器失败的解决方法

在pycharm中我们有时需要切换python的版本,这里需要注意的是我们是在PyCharm中的Preferences中切换的, 在File的Setting中切换可能会导致失败 以上...

Python的Flask站点中集成xhEditor文本编辑器的教程

Python的Flask站点中集成xhEditor文本编辑器的教程

xhEditor简介 xhEditor是一个基于jQuery开发的简单迷你并且高效的可视化HTML编辑器,基于网络访问并且兼容IE 6.0+, Firefox 3.0+, Opera 9...

python 实现矩阵上下/左右翻转,转置的示例

python中没有二维数组,用一个元素为list的list(matrix)保存矩阵,row为行数,col为列数 1. 上下翻转:只需要把每一行的list交换即可 for i in r...

跟老齐学Python之Import 模块

跟老齐学Python之Import 模块

认识模块 对于模块,在前面的一些举例中,已经涉及到了,比如曾经有过:import random (获取随机数模块)。为了能够对模块有一个清晰的了解,首先要看看什么模块,这里选取官方文档中...

python wxpython 实现界面跳转功能

python wxpython 实现界面跳转功能

用wxpython设计界面时可能会出现界面嵌套的情况 这样就需要进行界面的跳转 但是貌似wxpython没提供界面跳转的方式(也可能是我菜。。。) 所以就需要借助threading模块...