使用pymysql 操作MySQL数据库
安装
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数据库的更多相关文章
- flask + pymysql操作Mysql数据库
安装flask-sqlalchemy.pymysql模块 pip install flask-sqlalchemy pymysql ### Flask-SQLAlchemy的介绍 1. ORM:Obj ...
- 用pymysql操作MySQL数据库
工具库安装 pip install pymysql 连接关闭数据库与增删改查操作 # 导入pymysql库 import pymysql # 打开数据库连接 # 参数1:数据库服务器所在的主机+端口号 ...
- python使用pymysql操作mysql数据库
1.安装pymysql pip install pymysql 2.数据库查询示例 import pymysql # 连接database conn =pymysql.connect(user=' , ...
- PyMySQL操作mysql数据库(py3必学)
一,安装PyMySQL Python是编程语言,MySQL是数据库,它们是两种不同的技术:要想使Python操作MySQL数据库需要使用驱动.这里选用PyMySQL驱动. 安装方式还是使用pip命令. ...
- pymysql操作mysql数据库
1.建库 import pymysql # 建库 try: conn=pymysql.connect( host='127.0.0.1', port=3306, user='root', passwd ...
- python 3.6 +pyMysql 操作mysql数据库
版本信息:python:3.6 mysql:5.7 pyMysql:0.7.11 ########################################################### ...
- 使用pymysql操作mysql数据库
PyMySQL的安装和连接 PyMySQL的安装 python3. -m pip install pymysql python连接数据库 import pymysql # 创建连接 conn = py ...
- pymysql操作mysql
一.使用PyMySQL操作mysql数据库 适用环境 python版本 >=2.6或3.3 mysql版本>=4.1 安装 可以使用pip安装也可以手动下载安装.使用pip安装,在命令行执 ...
- python【第十二篇下】操作MySQL数据库以及ORM之 sqlalchemy
内容一览: 1.Python操作MySQL数据库 2.ORM sqlalchemy学习 1.Python操作MySQL数据库 2. ORM sqlachemy 2.1 ORM简介 对象关系映射(英语: ...
随机推荐
- 进程与线程(3)- python实现多线程
参考链接: https://www.jianshu.com/p/415976668b97?utm_campaign=maleskine&utm_content=note&utm_med ...
- Java | 基础归纳 | Gson && Json
JSON: JSON就是一种数据的组织形式,用于数据传输. 地址:https://mvnrepository.com/artifact/net.sf.json-lib/json-lib/2.4 Mav ...
- bzoj 4513 [Sdoi2016]储能表
题面 https://www.lydsy.com/JudgeOnline/problem.php?id=4513 题解 要求的式子 用数位dp的方法去做 我们把式子拆开 变成 $\sum_{i=0}^ ...
- 洛谷 P2398 GCD SUM || uva11417,uva11426,uva11424,洛谷P1390,洛谷P2257,洛谷P2568
https://www.luogu.org/problemnew/show/P2398 $原式=\sum_{k=1}^n(k\sum_{i=1}^n\sum_{j=1}^n[(i,j)=k])$ 方法 ...
- 简单几何(求交点) UVA 11178 Morley's Theorem
题目传送门 题意:莫雷定理,求三个点的坐标 分析:训练指南P259,用到了求角度,向量旋转,求射线交点 /*********************************************** ...
- vue文件中style标签的几个标识符
.vue文件中style标签的几个标识符 在人生就要绝望的时候, 被编辑器所提示的一个scopedSlots所拯救. 卧槽, 写到最后才发现这个属性的具体卵用. 详情见最后解决办法. 问题背景 问题由 ...
- word2vec的Java源码【转】
一.核心代码 word2vec.java package com.ansj.vec; import java.io.*; import java.lang.reflect.Array; import ...
- C#: static关键字的作用(转)
C#: static关键字的作用 static意思是静态,可以修饰类.字段.属性.方法 标记为static的就不用创建实例对象调用了,可以通过类名直接点出来 static三种用法: 1.用于变量前 ...
- spring mvc URL忽略大小写
@Configuration public class SpringWebConfig extends WebMvcConfigurationSupport { @Override public vo ...
- ES6学习笔记(6)----函数的扩展
参考书<ECMAScript 6入门>http://es6.ruanyifeng.com/ 函数的扩展 函数的默认值 : ES6可以为函数指定默认值 (1)指定默认值的两种方式 a.函数参 ...