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

发布时间:2020-08-25 04:49:43 作者:no-96
来源:脚本之家 阅读:149

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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对亿速云的支持。如果你想了解更多相关内容请查看下面相关链接

推荐阅读:
  1. 简单的Dockerfile书写(实例!!!)
  2. 简单操作mysql数据库介绍

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python mysql 操作

上一篇:Python字典底层实现原理详解

下一篇:多表查询sql语句(5表)

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》