安装
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. pyrcharm 编程规范

    正常变量赋值, 等号左右各一个空格: 参数赋值, 等号左右都没有空格: 注释#后面一个空格 类定义和函数定义,前后各两行,而在类的里面定义成员函数,只需要空一行 文件最后一个空行 变量.函数.类最好都 ...

  2. DFS HDOJ 5348 Ponds

    题目传送门 题意:有一张无向图,度数小于2的点会被去掉,直到全都大于等于2,问连通块顶点数为奇数的权值和为多少 分析:首先DFS把度数小于2的vis掉,第二次DFS把属于同一个连通块的vis掉,检查是 ...

  3. 题解报告:hdu 4607 Park Visit(最长链)

    Problem Description Claire and her little friend, ykwd, are travelling in Shevchenko's Park! The par ...

  4. 简单记录下@RequestBody(关于它和@RequestParam接收数据方式的拓展)

    内容参考自博客:https://blog.csdn.net/ff906317011/article/details/78552426 这个标注是用来注释controller中的请求方法中的参数的,那么 ...

  5. [在读]HTML5程序设计(第二版)

    去年买的,看了30%不到,之后一直是搁置状态,内容还不错,确确实实纯粹讲H5的.

  6. AJPFX关于StringBuffer,StringBuilder类总结(二)

    StringBuffer,StringBuilder类 总结2需要注意的知识点:1):// String -- >StringBuffer        String s = "hel ...

  7. Android提供的对话框

    1.普通对话框: 给出提示信息,有yes.no两个按钮. AlertDialog dialog=new AlertDialog.Builder(this) //this代表当前Activity对象,表 ...

  8. [转]彻底明确怎样设置minSdkVersion和targetSdkVersion

    minSdkVersion和targetSdkVersion相信非常多人都不太理解.我在网上也看了很多关于这两者差别的文章,感觉说的都非常模糊.直到我在stackOverFlow看到Android M ...

  9. EventBus 报“Subscriber class already registered to event class”错误

    这句子的话意思也很容易理解,“接收者类已经被注册为事件类了”. 之前我是这么写: 事件注册是写在onStart()里面的 @Override protected void onStart() { su ...

  10. java 之 插入排序

    思想:将一个数组分成两组,左边那组始终有序,每次取右边那组插入到左边适当的位置,保证左边有序,当右边没有需要插入的数据的时候,整个数组是有序的.插入排序是稳定排序. 注:此图引用自https://ww ...