概述
本文为大家分享了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',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,)) result = cursor.fetchone() print(result) finally: connection.close()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。
总结
以上是编程之家为你收集整理的Python3.6简单操作Mysql数据库全部内容,希望文章能够帮你解决Python3.6简单操作Mysql数据库所遇到的程序开发问题。
如果您也喜欢它,动动您的小指点个赞吧