最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

介绍Python3.6简单操作Mysql数据库的方法

来源:动视网 责编:小OO 时间:2020-11-27 14:22:54
文档

介绍Python3.6简单操作Mysql数据库的方法

本文为大家分享了Python3.6操作Mysql数据库的具体实例,供大家参考,具体内容如下:安装pymysql;参考https://github.com/PyMySQL/PyMySQL/。pip install pymsql。实例一;
推荐度:
导读本文为大家分享了Python3.6操作Mysql数据库的具体实例,供大家参考,具体内容如下:安装pymysql;参考https://github.com/PyMySQL/PyMySQL/。pip install pymsql。实例一;


这篇文章主要为大家详细介绍了Python3.6简单操作Mysql数据库,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文为大家分享了Python3.6操作Mysql数据库的具体实例,供大家参考,具体内容如下

安装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()

文档

介绍Python3.6简单操作Mysql数据库的方法

本文为大家分享了Python3.6操作Mysql数据库的具体实例,供大家参考,具体内容如下:安装pymysql;参考https://github.com/PyMySQL/PyMySQL/。pip install pymsql。实例一;
推荐度:
标签: 操作 使用 介绍
  • 热门焦点

最新推荐

猜你喜欢

热门推荐

专题
Top