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设计】的支持。如果你想了解更多相关内容请查看下面相关链接

相关文章

Python 高级专用类方法的实例详解

Python 高级专用类方法的实例详解 除了 __getitem__ 和 __setitem__ 之外 Python 还有更多的专用函数。某些可以让你模拟出你甚至可能不知道的功能。下面的...

Python Mysql自动备份脚本

测试系统环境  Windows 2003   python 2.5.1  mysql ...

基于Python执行dos命令并获取输出的结果

这篇文章主要介绍了基于Python执行dos命令并获取输出的结果,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 import os...

Python socket实现简单聊天室

本文实例为大家分享了Python socket实现简单聊天室的具体代码,供大家参考,具体内容如下 服务端使用了select模块,实现了对多个socket的监控。客户端由于select在W...

Python中运行并行任务技巧

Python中运行并行任务技巧

示例 标准线程多进程,生产者/消费者示例: Worker越多,问题越大 复制代码 代码如下: # -*- coding: utf8 -*- import os import time i...