安装
pip install pymysql 注:连接前要有可使用的账户及有权限、可操作的数据库 先来一个栗子:
import pymysql # 连接database
conn = pymysql.connect(
host=“你的数据库地址”,
user=“用户名”,
password=“密码”,
database=“数据库名”,
charset=“utf8” ) # 获取一个可以执行SQL语句的光标对象
cursor = conn.cursor() # 将结果作为字典返回的游标
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 定义要执行的SQL语句
sql = """
CREATE TABLE USER1 (
id INT auto_increment PRIMARY KEY ,
name CHAR(10) NOT NULL UNIQUE,
age TINYINT NOT NULL
)ENGINE=innodb DEFAULT CHARSET=utf8;
""" cursor.execute(sql) # 执行SQL语句
cursor.close() # 关闭光标对象
conn.close() # 关闭数据库连接

增删改操作:

import pymysql

conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
cursor = conn.cursor() # 默认获取的数据是元祖类型
# cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 游标设置为字典类型 try:
# 返回受影响行数
# cursor.execute(sql,[user,pwd]) # 传参 列表,元组,字典皆可
effect_row = cursor.execute("update tb1 set pwd = '123' where id = %s", (11,))
   
# sql = "select * from userinfo where username=%(use)s and password=%(pas)s"
# cursor.execute(sql,{'use':user,'pas':pwd}) # 批量执行多条SQL语句,列表套元组传参[(,),(,)]
effect_row = cursor.executemany("insert into tb1(user,pwd,age)values(%s,%s,%s)", [("user1","pwd1","111"),("user2","pwd2","222")]) # 增删改都提交,不然无法保存数据
conn.commit() # 提交之后,可获取刚插入的数据的ID,插入多条数据拿到的是最后一条的ID
last_id = cursor.lastrowid except Exception as e: # 插入数据失败时, 回滚事务
conn.rollback() cursor.close()
conn.close()
 

查:

import pymysql

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='t1')
cursor = conn.cursor()
cursor.execute(sql) row_1 = cursor.fetchone() # 获取单条查询数据
row_2 = cursor.fetchmany(3) # 可以获取指定数量的数据
row_3 = cursor.fetchall() # 获取多条查询数据 注:在fetch数据时按照顺序进行,可以使用cursor.scroll(num,mode)来移动游标位置
## 光标按绝对位置移动1
## cursor.scroll(1, mode="absolute")
## 光标按照相对位置(当前位置)移动1
## cursor.scroll(1, mode="relative") cursor.close()
conn.close()

简单封装:

import pymysql
from mypy3 import settings class SqlHelper(object):
def __init__(self):
self.host = settings.host
self.port = settings.port
self.user = settings.user
self.passwd = settings.passwd
self.db = settings.db
self.charset = settings.charset
self.connect() def connect(self):
self.conn = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db, charset=self.charset)
self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor) def create(self,sql,args):
'''创建'''
self.cursor.execute(sql,args)
self.conn.commit()
return self.cursor.lastrowid def get_one(self, sql, args):
'''fetchone'''
self.cursor.execute(sql, args)
return self.cursor.fetchone() def get_list(self, sql, args=None):
'''fetchall'''
self.cursor.execute(sql, args)
return self.cursor.fetchall() def modify(self,sql,args):
'''增删改'''
self.cursor.execute(sql,args)
self.conn.commit() def multiple_modify(self,sql,args):
'''批量增删改'''
# self.cursor.executemany('insert into bd(id,name)values(%s,%s)',[(1,'name1'),(2,'name2')])
self.cursor.executemany(sql,args)
self.conn.commit() def close(self):
self.cursor.close()
self.conn.close() def __del__(self):
self.close()

使用pymysql 操作MySQL数据库的更多相关文章

  1. flask + pymysql操作Mysql数据库

    安装flask-sqlalchemy.pymysql模块 pip install flask-sqlalchemy pymysql ### Flask-SQLAlchemy的介绍 1. ORM:Obj ...

  2. 用pymysql操作MySQL数据库

    工具库安装 pip install pymysql 连接关闭数据库与增删改查操作 # 导入pymysql库 import pymysql # 打开数据库连接 # 参数1:数据库服务器所在的主机+端口号 ...

  3. python使用pymysql操作mysql数据库

    1.安装pymysql pip install pymysql 2.数据库查询示例 import pymysql # 连接database conn =pymysql.connect(user=' , ...

  4. PyMySQL操作mysql数据库(py3必学)

    一,安装PyMySQL Python是编程语言,MySQL是数据库,它们是两种不同的技术:要想使Python操作MySQL数据库需要使用驱动.这里选用PyMySQL驱动. 安装方式还是使用pip命令. ...

  5. pymysql操作mysql数据库

    1.建库 import pymysql # 建库 try: conn=pymysql.connect( host='127.0.0.1', port=3306, user='root', passwd ...

  6. python 3.6 +pyMysql 操作mysql数据库

    版本信息:python:3.6 mysql:5.7 pyMysql:0.7.11 ########################################################### ...

  7. 使用pymysql操作mysql数据库

    PyMySQL的安装和连接 PyMySQL的安装 python3. -m pip install pymysql python连接数据库 import pymysql # 创建连接 conn = py ...

  8. pymysql操作mysql

    一.使用PyMySQL操作mysql数据库 适用环境 python版本 >=2.6或3.3 mysql版本>=4.1 安装 可以使用pip安装也可以手动下载安装.使用pip安装,在命令行执 ...

  9. python【第十二篇下】操作MySQL数据库以及ORM之 sqlalchemy

    内容一览: 1.Python操作MySQL数据库 2.ORM sqlalchemy学习 1.Python操作MySQL数据库 2. ORM sqlachemy 2.1 ORM简介 对象关系映射(英语: ...

随机推荐

  1. USB转串口 FT232/PL2303芯片使用体会

    现在笔记本上很少带有串口了,而串口又是做电子设计必备的通讯接口之一,好在USB转串口比较方便,市面上常用的USB转串口芯片有很多,最常见的有FT232.PL2303.CH340三种 原理:单片机的TX ...

  2. memcached原理及介绍

    memcached是一种缓存技术,在存储在内存中(高性能分布式内存缓存服务器).目的 : 提速.(传统的都是把数据保存在关系型数据库管理系统既RDBMS,客户端请求时会从RDBS中读取数据并在浏览器中 ...

  3. JS获取屏幕的大小

    <html><script>function a(){document.write("屏幕分辨率为:"+screen.width+"*" ...

  4. SP1805 Largest Rectangle in a Histogram

    题目链接: 洛谷SP1805 题意: 如图所示,在一条水平线上有n个宽为1的矩形,求包含于这些矩形的最大子矩形面积(图中的阴影部分的面积即所求答案) 输入格式: 有多组测试数据,每组数据占一行.输入零 ...

  5. Travelling HDU - 3001

    Travelling HDU - 3001 方法:3进制状态压缩dp(更好的方法是预处理出每个状态数字对应的y数组,然后用刷表,时间复杂度可以少一个n) #include<cstdio> ...

  6. 简单了解Linux中 du 和 df 以及它们的区别

    一 .du : 显示每个文件和目录的磁盘使用空间~~~文件的大小. 命令参数: -a   #显示目录中文件的大小  单位 KB . -b  #显示目录中文件的大小,以字节byte为单位. -c  #显 ...

  7. hdu 1979 DFS + 字典树剪枝

    http://acm.hdu.edu.cn/showproblem.php?pid=1979 Fill the blanks Time Limit: 3000/1000 MS (Java/Others ...

  8. RHEL 6.5----CDN(lumanger)

    主机名  IP   服务 master 192.168.30.130  CDN(LuManager) slave 192.168.30.131  DNS  软件安装包下载地址及安装方法 http:// ...

  9. [转]Intellij Idea自动添加注释的方法

    Intellij Idea自动添加注释的方法 阿历Ali 关注 2017.08.20 21:22* 字数 914 阅读 2741评论 0喜欢 6 程序媛阿历终于要写第一篇关于开发的文章了!!! 阿历用 ...

  10. 【学习笔记】响应式布局的常用解决方案(媒体查询、百分比、rem、和vw/vh)

    原文转载:https://blog.csdn.net/sinat_17775997/article/details/81020417 一.媒体查询 不同物理分辨率的设备,在还原设计稿时,css中设置的 ...