笔记-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. arcgis Flex QueryTask

    <esri:Map id="myMap" creationComplete="useMapServicePermaLink()" load="u ...

  2. selenium找不到元素

    1.页面元素处于不显示状态时,找不元素.必须使元素处于显示状态.使用js 或者 元素的点击事件等方式可以实现. " src="index.php?m=Index&a=Men ...

  3. 百万级数据库SQL优化大总结

    网上关于SQL优化的教程很多,但是比较杂乱.近日有空整理了一下,写出来跟大家分享一下,其中有错误和不足的地方,还请大家纠正补充. 这篇文章我花费了大量的时间查找资料.修改.排版,希望大家阅读之后,感觉 ...

  4. bootstrap-table 数据表格行内修改

    bootstrap-table 数据行内修改js中设置列的属性 editable : { type : 'text',//数据显示在文本框内 emptytext : "--",// ...

  5. 使用C语言来实现模块化

    除了C语言以及C++编程语言之外,在其它现在非常流行的开发语言中,比如说:java,php,jsp等等.我们很难想象到缺少标准化的模块管理机制是一件多么可怕的事情.但是这往往也是由C语言本身的设计哲学 ...

  6. nginx处理HTTP header问题

    在实际开发中遇到http header 自定义key中包含下划线(_)时服务端header丢失的问题,解决办法详细见以下网页内容,感谢原博主 http://blog.csdn.net/dac55300 ...

  7. 洛谷 P2814 家谱

    题目背景 现代的人对于本家族血统越来越感兴趣. 题目描述 给出充足的父子关系,请你编写程序找到某个人的最早的祖先. 输入输出格式 输入格式: 输入由多行组成,首先是一系列有关父子关系的描述,其中每一组 ...

  8. To my dear friends in SFAE

    To my dear friends in SFAE, 这不是farewell,我还在西门子大家庭.2018年1月份我会转到SLC MCBU.在SFAE十年,一些敢想,唠叨唠叨~ 十年弹指一挥间.记得 ...

  9. javascript中的循环引用对象处理

    先说明一下什么是循环引用对象: var a={"name":"zzz"}; var b={"name":"vvv"}; ...

  10. TCP的可靠连接是如何产生的?

    http://bbs.csdn.net/topics/190011812 看过TCP/IP的源代码没?tcp中所谓的连接只是在tcp的tcb中存储了对端的地址信息,并且记录连接的状态,通过重发之类的来 ...