Python3.6简单的操作Mysql数据库的三个实例
2018-10-17 14:19
1116 查看
安装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验证码识别教程之灰度处理、二值化、降噪与tesserocr识别
- Python中Proxypool库的安装与配置
- Python运维开发之psutil库的使用详解
- 对python3中pathlib库的Path类的使用详解
- Python的argparse库使用详解
- 让代码变得更易维护的7个Python库
- 3个用于数据科学的顶级Python库
- 用于业余项目的8个优秀Python库
- Python爬虫常用库的安装及其环境配置
- Python连接Mssql基础教程之Python库pymssql
- Python爬虫基础之XPath语法与lxml库的用法详解
- python3结合openpyxl库实现excel操作的实例代码
- Python wxPython库Core组件BoxSizer用法示例
- Tesserocr库的正确安装方式
相关文章推荐
- python 3.6 +pyMysql 操作mysql数据库(实例讲解)
- Python3.6简单操作Mysql数据库
- Python3.6简单的操作Mysql数据库
- Python操作使用MySQL数据库的实例代码
- python中操作文件函数open的简单操作实例
- Python3.6简单反射操作示例
- Python操作MySQL数据库9个实用实例
- Python 简单操作Mysql数据库模块详解
- python 操作mysql数据库(简单/基础)
- Python 操作mongodb 简单实例
- 用python操作mysql数据库(之简单“插入数据”操作)
- Python操作MySQL数据库9个实用实例
- Python 3.6 字符串操作 实例
- python中操作文件函数open的简单操作实例
- Mysql入门笔记(2):Python操作MySQL数据库9个实用实例
- Python语句中基本的规则与特殊字符简单操作实例
- Python操作MySQL数据库9个实用实例
- Python MySQLdb模块连接操作mysql数据库实例
- Python MySQLdb模块连接操作mysql数据库实例_python
- Python操作MySQL数据库实例