使用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简介 对象关系映射(英语: ...
随机推荐
- (7)awk命令(每周一个linux命令系列)
简介 awk是一个强大的文本分析工具,尤其是在应对格式化比较好的日志文件时,简单来说awk就是把文件逐行的读入,以空格为默认分隔符(也可以指定分隔符)将每行切片处理. 语法 awk [选项参数] 's ...
- iOS 在UITextView中查找某个Range所在的Rect
代码如下(Swift 4): extension UITextView { /// 查找文本范围所在的矩形范围 /// /// - Parameter range: 文本范围 /// - Return ...
- bzoj 4909 [Sdoi2017]龙与地下城
题面 https://www.lydsy.com/JudgeOnline/problem.php?id=4909 题解 目前为止仅仅在LOJ上A掉这道题(Loj真快!) 当然不是标准做法 显然我们只要 ...
- Hdu 2089 不要62 (数位dp入门题目)
题目链接: Hdu 2089 不要62 题目描述: 给一个区间 [L, R] ,问区间内不含有4和62的数字有多少个? 解题思路: 以前也做过这个题目,但是空间复杂度是n.如果数据范围太大就GG了.今 ...
- linux常用的shell命令
1.shell介绍 shell(外壳)是linux系统的最外层,简单的说,它就是用户和操作系统之间的一个命令解释器. 2.shell命名的使用 ls :查看当前目录的信息,list . ...
- PowerShell~发布你的mvc网站
通过使用ps加上msbuild可以方便的编译你的.net应用程序,并且可以把它发布到你的磁盘上,部署非常方例! 我们在c盘添加一个hello网站,解决方案名是hello.sln,它的网站是hello. ...
- [转]如何使用MFC和类型库创建自动化项目
本文转自:http://www.cnblogs.com/zhoug2020/archive/2012/04/01/2429064.html 摘要 本文详细介绍了如何自动化像Microsoft Offi ...
- jQuery选择器之可见性选择器
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content ...
- 从 fn_dbLog 解析操作日志(补充update)
过去经常听到SQL server 日志,可是在提供的界面上看到的Log不是我们想要的,我们想窥探具体的数据操作日志.专业恢复追踪数据库操作日志的软件:ApexSQLLog,偶然发现SQL Server ...
- https为数据传输保驾护航
为什么要使用https 谷歌官网已宣布,今年7月起,Chrome浏览器的地址栏将把所有HTTP标示为不安全网站. 在客户端与服务器数据传输过程中,http协议传输是不安全的,一般情况下,http协议的 ...