笔记-python操作mysql
笔记-python操作mysql
1. 开始
1.1. 环境准备-mysql
create database db_python;
use db_python;
create table `t2`(
`id` int unsigned auto_increment,
`name` varchar(30),
primary key(`id`));
#创建用户并授权
create user 'dev_python' identified by '123456';
grant all on db_python.t2 to dev_python@'%';
alter table t2 add password varchar(30);
alter table t2 add content varchar(500);
1.2. 环境-python
使用pymysql库,PyMySQL是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中是使用mysqldb。
pip install pymysql
2. API
2.1. connect
连接类,有一些参数可以调整,列出最常用的部分:
# connect to database, parameter: address, user name, password, database name,charset
db = pymysql.connect('localhost','dev_python','123456','db_python',cursorclass=pymysql.cursors.DictCursor)
2.2.
cursor
执行操作的接口,有
execute(query, args=None)
Execute a query
|
Parameters: |
query (str) – Query to execute. args (tuple, list or dict) – parameters used with query. (optional) |
|
Returns: |
Number of affected rows |
|
Return type: |
If args is a list or tuple, %s can be used
as a placeholder in the query. If args is a dict, %(name)s can be used as a placeholder in the query.
fetchall()
Fetch all the rows
fetchmany(size=None)
Fetch several rows
fetchone()
Fetch the next row
classpymysql.cursors.DictCursor(connection)
A cursor which returns results as a
dictionary
返回的是一个字典,使用时需要注意返回的字典的健值。
3.
使用
import pymysql
# connect to database, parameter: address, user name, password,
database name,charset
db = pymysql.connect('localhost','dev_python','123456','db_python',cursorclass=pymysql.cursors.DictCursor)
'''
# 得到一个可以执行sql语句的cursor object
# 注意cursor支持上下文,
# with db.cursor() as cur:
cursor = db.cursor()
#定义要执行的sql语句
# 本处为查看表结构
cmd_text = 'desc t2;'
# 执行
print(cursor.execute(cmd_text))
# 关闭相关对象
cursor.close()
db.close()
'''
# execute statement
#create table
sql_create = r"""create table if not
exists `t3` (`id` int)"""
with db.cursor() as cur:
cur.execute(sql_create)
print(cur.execute('show
tables;'))
print(cur.fetchall())
#CURD
# 插入
cmd_insert = """insert into t2
values('7','first_name','pass1', 'content1')"""
with db.cursor() as cur:
pass
#print(cur.execute(cmd_insert))
db.commit()
# update
sql_update = """update t2 set name=%s
where id=%s"""
with db.cursor() as cur:
cur.execute(sql_update, ['ppp','7'])
cur.execute('select * from t2')
#print(cur.fetchall())
# retrieve
sql_select = """select * from
t3;"""
with db.cursor() as cur:
if cur.execute(sql_select):
print(cur.fetchall())
else:
print('get 0
rows.')
# delete
sql_delete = """delete from t2 where
id=%s"""
with db.cursor() as cur:
cur.execute(sql_delete, ['7'])
cur.execute('select * from t2')
print(cur.fetchall())
上面列出的仅包括最常用的CURD操作,更复杂的功能需要参考相关接口文档。
4.
参考文档
https://pypi.org/project/PyMySQL/
https://pymysql.readthedocs.io/en/latest/
笔记-python操作mysql的更多相关文章
- mysql数据库----python操作mysql ------pymysql和SQLAchemy
本篇对于Python操作MySQL主要使用两种方式: 原生模块 pymsql ORM框架 SQLAchemy 一.pymysql pymsql是Python中操作MySQL的模块,其使用方法和MySQ ...
- Python(九) Python 操作 MySQL 之 pysql 与 SQLAchemy
本文针对 Python 操作 MySQL 主要使用的两种方式讲解: 原生模块 pymsql ORM框架 SQLAchemy 本章内容: pymsql 执行 sql 增\删\改\查 语句 pymsql ...
- 练习:python 操作Mysql 实现登录验证 用户权限管理
python 操作Mysql 实现登录验证 用户权限管理
- Python操作MySQL
本篇对于Python操作MySQL主要使用两种方式: 原生模块 pymsql ORM框架 SQLAchemy pymsql pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb ...
- Python操作Mysql之基本操作
pymysql python操作mysql依赖pymysql这个模块 下载安装 pip3 install pymysql 操作mysql python操作mysql的时候,是通过”游标”来进行操作的. ...
- python成长之路【第十三篇】:Python操作MySQL之pymysql
对于Python操作MySQL主要使用两种方式: 原生模块 pymsql ORM框架 SQLAchemy pymsql pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎 ...
- python操作mysql数据库的相关操作实例
python操作mysql数据库的相关操作实例 # -*- coding: utf-8 -*- #python operate mysql database import MySQLdb #数据库名称 ...
- Python 操作 MySQL 之 pysql 与 ORM(转载)
本文针对 Python 操作 MySQL 主要使用的两种方式讲解: 原生模块 pymsql ORM框架 SQLAchemy 本章内容: pymsql 执行 sql 增\删\改\查 语句 pymsql ...
- Python开发【第十九篇】:Python操作MySQL
本篇对于Python操作MySQL主要使用两种方式: 原生模块 pymsql ORM框架 SQLAchemy pymsql pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb ...
随机推荐
- iframe跨域上传图片
方案一:用jquery的$.post异步提交,然后把返回来的值用jquery填充到隐藏域中.可是$.post不支持跨域. jQuery.ajax()支持get方式的跨域,这其实是采用jsonp的方式来 ...
- Row_number() OVER(PARTITION BY xxx ORDER BY XXX)分组排序
--//创建一个信息表 ,) ,),st_name ),class ),score ,)) --//插入测试数据============start=================== insert ...
- Azure 5 月新公布
Azure 5 月新发布:CDN 高级版服务降价,MySQL Database 高级版本和新功能,以及应用程序网关中的 WAF 层发布 Azure CDN 高级版服务自 2017 年 5 月 1 ...
- 西门子触摸屏利用VBScript脚本创建csv文件
功能描述:利用VBScript脚本创建csv/txt文件 有时需要将PLC或运动控制器Simotion中的数据写到SD卡或U盘上.一种实现方法是,如果使用的是精致面板(comfort panel),可 ...
- 双击易语言没有反应,按住shift再双击可解决
参考资料:http://tieba.baidu.com/p/2987732743 的7楼.
- leetcode: 复杂度
1. single-number Given an array of integers, every element appears twice except for one. Find that s ...
- CRUD全栈式编程架构之MVC的扩展设计
MVC执行流程 路由的扩展 我理解的路由作用有以下几个 Seo优化,用“/”分开的url爬虫更爱吃 物理和逻辑文件分离,url不再按照文件路径映射 Controller,Action的选择 MVC路由 ...
- IOS instancetype的使用好处
instancetype的类型表示上,跟id一样,可以表示任何对象类型 instancetype只能用在返回值类型上,不能像 id 一样用在参数类型上 instancetype 比 id 多一个好处 ...
- 【CCPC-Wannafly Winter Camp Day3 (Div1) D】精简改良(状压DP)
点此看题面 大致题意: 给你一张图,定义\(dis(i,j)\)为\(i\)与\(j\)的最短距离,现要求删去若干条边,使得图仍然联通,且\(\sum_{i=1}^n\sum_{j=i+1}^ndis ...
- MyBatis中解决字段名与实体类属性名不相同的冲突
一: 通过在查询的sql语句中定义字段名的别名,让字段名的别名和实体类的属性名一致,这样就可以表的字段名和实体类的属性名一一对应上了,这种方式是通过在sql语句中定义别名来解决字段名和属性名的映射关系 ...