笔记-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 (tuplelist or dict) – parameters used with query. (optional)

Returns:

Number of affected rows

Return type:

int

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的更多相关文章

  1. mysql数据库----python操作mysql ------pymysql和SQLAchemy

    本篇对于Python操作MySQL主要使用两种方式: 原生模块 pymsql ORM框架 SQLAchemy 一.pymysql pymsql是Python中操作MySQL的模块,其使用方法和MySQ ...

  2. Python(九) Python 操作 MySQL 之 pysql 与 SQLAchemy

    本文针对 Python 操作 MySQL 主要使用的两种方式讲解: 原生模块 pymsql ORM框架 SQLAchemy 本章内容: pymsql 执行 sql 增\删\改\查 语句 pymsql ...

  3. 练习:python 操作Mysql 实现登录验证 用户权限管理

    python 操作Mysql 实现登录验证 用户权限管理

  4. Python操作MySQL

    本篇对于Python操作MySQL主要使用两种方式: 原生模块 pymsql ORM框架 SQLAchemy pymsql pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb ...

  5. Python操作Mysql之基本操作

    pymysql python操作mysql依赖pymysql这个模块 下载安装 pip3 install pymysql 操作mysql python操作mysql的时候,是通过”游标”来进行操作的. ...

  6. python成长之路【第十三篇】:Python操作MySQL之pymysql

    对于Python操作MySQL主要使用两种方式: 原生模块 pymsql ORM框架 SQLAchemy pymsql pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎 ...

  7. python操作mysql数据库的相关操作实例

    python操作mysql数据库的相关操作实例 # -*- coding: utf-8 -*- #python operate mysql database import MySQLdb #数据库名称 ...

  8. Python 操作 MySQL 之 pysql 与 ORM(转载)

    本文针对 Python 操作 MySQL 主要使用的两种方式讲解: 原生模块 pymsql ORM框架 SQLAchemy 本章内容: pymsql 执行 sql 增\删\改\查 语句 pymsql ...

  9. Python开发【第十九篇】:Python操作MySQL

    本篇对于Python操作MySQL主要使用两种方式: 原生模块 pymsql ORM框架 SQLAchemy pymsql pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb ...

随机推荐

  1. laravel下的ORM数据映射之自由畅想

    此处以Model::get()方法和Model::first()方法为例 public static function get($data=[]){//默认是空数组 if(count($data)== ...

  2. canvas绘制圆环

  3. Implementation with Java

    Implementation with Java From:http://jcsc.sourceforge.net In general, follow the Sun coding conventi ...

  4. Java—多态

    多态——对象的多种形态(继承是多态实现的基础) 引用多态:父类的引用可以指向本类的对象:父类的引用可以指向子类的对象 方法多态:创建本类对象时,调用的方法为本类方法:创建子类对象时,调用的方法为子类重 ...

  5. springboot 修改和设置 banner

    springboot 修改和设置 banner 先上图 修改步骤 1.在src/main/resources下新建一个banner.txt文档 2.通过http://patorjk.com/softw ...

  6. 整理齐全 - Vultr VPS自定义安装Windows ISO(2003/2012/2008/WIN7)

    最近公司有几个项目是需要在Windows VPS服务器中运行调试的,但是公司给予的成本有限,所以只能在Linux VPS中考虑,毕竟Linux服务器相比Windows系统便宜很多.开始我们运维部门考虑 ...

  7. 笨办法学Python(八)

    习题 8: 打印,打印 formatter = "%r %r %r %r" print formatter % (1, 2, 3, 4) print formatter % (&q ...

  8. thinkphp 去掉URL 里面的index.php

    例如你的原路径是 http://localhost/test/index.php/home/goods/index.html 那么现在的地址是 http://localhost/test/home/g ...

  9. IOS照相机的启动,图片的读取,存储demo

    #import @interface ViewController : UIViewController@property (retain, nonatomic) IBOutlet UIImageVi ...

  10. IOS 拉伸图片(封装)

    /** * 根据图片名返回一张能够自由拉伸的图片 */ +(UIImage *)resizedImage:(NSString *)name { UIImage *image=[UIImage imag ...