使用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简介 对象关系映射(英语: ...
随机推荐
- redis的多路复用io
redis基于reactor开发了自己的网路事件处理器,被称为文件事件处理器.使用io多路复用来同时监听多个套接字,来响应客户端的连接应答.命令请求.命令恢复.多路复用技术使得redis可以使用单进程 ...
- ie下,php HTTP_REFERER获取失败的整理
HTTP_REFERER有效的情况1.以iframe 形式调用地址2.以window.open调用,打开新页面window.open(url);3.使用window.location.replace在 ...
- selenium之webdriverAPI接口详解
1. 浏览器操作 driver.maximize_window() #最大化窗口driver.execute_script('window.scrollTo(0,0);') #滚动窗口到最上面driv ...
- Codeforces Round #325 (Div. 2)
水 A - Alena's Schedule /************************************************ * Author :Running_Time * Cr ...
- h5-26-web本地存储
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- Joystick
Joystick相当于5个按键的集合,向上.下.左.右.中间5个方向接通,经常用于游戏场合.
- c8051单片机注意事项:
一定要注意交叉开关问题:外设要想正确分配到指定引脚,一定要用配置工具确定分配到指定引脚:如果手动分配一定要仔细验证.这方面有个深刻的教训. 有个项目用c8051f020,用到2个串口,硬件已经确定好了 ...
- sql子查询的例子
1.单行子查询 select ename,deptno,sal from emp where deptno=(select deptno from dept ...
- poj3280 Cheapest Palindrome
思路: 区间dp.添加和删除本质相同. 实现: #include <iostream> #include <cstdio> using namespace std; int n ...
- 洛谷P2761 软件补丁问题(状压DP,SPFA)
题意 描述不清... Sol 网络流24题里面怎么会有状压dp?? 真是狗血,不过还是简单吧. 直接用$f[sta]$表示当前状态为$sta$时的最小花费 转移的时候枚举一下哪一个补丁可以搞这个状态 ...