简介

PyMySQL是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中是使用mysqldb。

安装

pip3 install pymysql

创建连接

#!/usr/bin/python3

import pymysql

# 打开数据库连接
db = pymysql.connect("localhost","root","password","test" ) # 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor() # 使用 execute() 方法执行 SQL,如果表存在则删除
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") # 使用预处理语句创建表
sql = """CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )""" cursor.execute(sql) # 关闭数据库连接
db.close()

#!/usr/bin/python3

import pymysql

# 打开数据库连接
db = pymysql.connect("localhost","root","password","test" ) # 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor() # 使用预处理语句创建表
sql = """insert into employee(first_name, last_name, age, sex, income)
values('sophie', 'Manche', 25, 'F', 3000)""" try:
cursor.execute(sql)
db.commit()
except:
db.rollback() # 关闭数据库连接
db.close()

#!/usr/bin/python3

import pymysql

# 打开数据库连接
db = pymysql.connect("localhost","root","password","test" ) # 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor() # 使用预处理语句创建表
sql = "delete from employee where age > %s" % (21) try:
cursor.execute(sql)
db.commit()
except:
db.rollback() # 关闭数据库连接
db.close()

#!/usr/bin/python3

import pymysql

# 打开数据库连接
db = pymysql.connect("localhost","root","password","test" ) # 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor() # 使用预处理语句创建表
sql = "update employee set age=age+1 where sex='%c'" % ('M') try:
cursor.execute(sql)
db.commit()
except:
db.rollback() # 关闭数据库连接
db.close()

#!/usr/bin/python3

import pymysql

# 打开数据库连接
db = pymysql.connect("localhost","root","password","test") # 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor() # 使用预处理语句创建表
sql = "select * from employee \
where income > %s" % (1000) try:
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
print("fname=%s,lname=%s,age=%s,sex=%s,income=%s" % \
(fname, lname, age, sex, income))
except:
print("Error:unable to fetch data") # 关闭数据库连接
db.close()

初始化函数详解

def __init__(self, host=None, user=None, password="",
database=None, port=0, unix_socket=None,
charset='', sql_mode=None,
read_default_file=None, conv=None, use_unicode=None,
client_flag=0, cursorclass=Cursor, init_command=None,
connect_timeout=10, ssl=None, read_default_group=None,
compress=None, named_pipe=None, no_delay=None,
autocommit=False, db=None, passwd=None, local_infile=False,
max_allowed_packet=16*1024*1024, defer_connect=False,
auth_plugin_map={}, read_timeout=None, write_timeout=None,
bind_address=None):
参数解释:
host: Host where the database server is located #主机名或者主机地址
user: Username to log in as #用户名
password: Password to use. #密码
database: Database to use, None to not use a particular one. #指定的数据库
port: MySQL port to use, default is usually OK. (default: 3306) #端口,默认是3306
bind_address: When the client has multiple network interfaces, specify
the interface from which to connect to the host. Argument can be
a hostname or an IP address. #当客户端有多个网络接口的时候,指点连接到数据库的接口,可以是一个主机名或者ip地址
unix_socket: Optionally, you can use a unix socket rather than TCP/IP.
charset: Charset you want to use. #指定字符编码
sql_mode: Default SQL_MODE to use.
read_default_file:
Specifies my.cnf file to read these parameters from under the [client] section.
conv:
Conversion dictionary to use instead of the default one.
This is used to provide custom marshalling and unmarshaling of types.
See converters.
use_unicode:
Whether or not to default to unicode strings.
This option defaults to true for Py3k.
client_flag: Custom flags to send to MySQL. Find potential values in constants.CLIENT.
cursorclass: Custom cursor class to use.
init_command: Initial SQL statement to run when connection is established.
connect_timeout: Timeout before throwing an exception when connecting.
(default: 10, min: 1, max: 31536000)
ssl:
A dict of arguments similar to mysql_ssl_set()'s parameters.
For now the capath and cipher arguments are not supported.
read_default_group: Group to read from in the configuration file.
compress; Not supported
named_pipe: Not supported
autocommit: Autocommit mode. None means use server default. (default: False)
local_infile: Boolean to enable the use of LOAD DATA LOCAL command. (default: False)
max_allowed_packet: Max size of packet sent to server in bytes. (default: 16MB)
Only used to limit size of "LOAD LOCAL INFILE" data packet smaller than default (16KB).
defer_connect: Don't explicitly connect on contruction - wait for connect call.
(default: False)
auth_plugin_map: A dict of plugin names to a class that processes that plugin.
The class will take the Connection object as the argument to the constructor.
The class needs an authenticate method taking an authentication packet as
an argument. For the dialog plugin, a prompt(echo, prompt) method can be used
(if no authenticate method) for returning a string from the user. (experimental)
db: Alias for database. (for compatibility to MySQLdb)
passwd: Alias for password. (for compatibility to MySQLdb)

cursor 函数详解

class Cursor(object):
"""
This is the object you use to interact with the database.
"""
def close(self):
"""
Closing a cursor just exhausts all remaining data.
"""
def setinputsizes(self, *args):
"""Does nothing, required by DB API.""" def setoutputsizes(self, *args):
"""Does nothing, required by DB API."""
def execute(self, query, args=None):
"""Execute a query :param str query: Query to execute. :param args: parameters used with query. (optional)
:type args: tuple, list or dict :return: Number of affected rows
:rtype: 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.
"""
def executemany(self, query, args):
# type: (str, list) -> int
"""Run several data against one query :param query: query to execute on server
:param args: Sequence of sequences or mappings. It is used as parameter.
:return: Number of rows affected, if any. This method improves performance on multiple-row INSERT and
REPLACE. Otherwise it is equivalent to looping over args with
execute().
"""
def fetchone(self):
"""Fetch the next row"""
def fetchmany(self, size=None):
"""Fetch several rows"""
def fetchall(self):
"""Fetch all the rows"""
......

参考:https://www.cnblogs.com/liubinsh/p/7568423.html

python系列之(5)PyMySQL的使用的更多相关文章

  1. Python系列之入门篇——MYSQL

    Python系列之入门篇--MYSQL 简介 python提供了两种mysql api, 一是MySQL-python(不支持python3),二是PyMYSQL(支持python2和python3) ...

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

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

  3. 总结整理 -- python系列

    python系列 python--基础学习(一)开发环境搭建,体验HelloWorld python--基础学习(二)判断 .循环.定义函数.继承.调用 python--基础学习(三)字符串单引号.双 ...

  4. 初探接口测试框架--python系列7

    点击标题下「蓝色微信名」可快速关注 坚持的是分享,搬运的是知识,图的是大家的进步,没有收费的培训,没有虚度的吹水,喜欢就关注.转发(免费帮助更多伙伴)等来交流,想了解的知识请留言,给你带来更多价值,是 ...

  5. 初探接口测试框架--python系列2

    点击标题下「蓝色微信名」可快速关注 坚持的是分享,搬运的是知识,图的是大家的进步,没有收费的培训,没有虚度的吹水,喜欢就关注.转发(免费帮助更多伙伴)等来交流,想了解的知识请留言,给你带来更多价值,是 ...

  6. 初探接口测试框架--python系列3

    点击标题下「微信」可快速关注 坚持的是分享,搬运的是知识,图的是大家的进步,没有收费的培训,没有虚度的吹水,喜欢就关注.转发(免费帮助更多伙伴)等来交流,想了解的知识请留言,给你带来更多价值,是我们期 ...

  7. 初探接口测试框架--python系列4

    点击标题下「蓝色微信名」可快速关注 坚持的是分享,搬运的是知识,图的是大家的进步,没有收费的培训,没有虚度的吹水,喜欢就关注.转发(免费帮助更多伙伴)等来交流,想了解的知识请留言,给你带来更多价值,是 ...

  8. 初探接口测试框架--python系列5

    点击标题下「蓝色微信名」可快速关注 坚持的是分享,搬运的是知识,图的是大家的进步,没有收费的培训,没有虚度的吹水,喜欢就关注.转发(免费帮助更多伙伴)等来交流,想了解的知识请留言,给你带来更多价值,是 ...

  9. 初探接口测试框架--python系列6

    点击标题下「蓝色微信名」可快速关注 坚持的是分享,搬运的是知识,图的是大家的进步,没有收费的培训,没有虚度的吹水,喜欢就关注.转发(免费帮助更多伙伴)等来交流,想了解的知识请留言,给你带来更多价值,是 ...

  10. Python自动化运维之18、Python操作 MySQL、pymysql、SQLAchemy

    一.MySQL 1.概述 什么是数据库 ? 答:数据的仓库,和Excel表中的行和列是差不多的,只是有各种约束和不同数据类型的表格 什么是 MySQL.Oracle.SQLite.Access.MS ...

随机推荐

  1. 3377加减乘除等于24(原生js实现)

    <!doctype html> <html> <head> <meta charset="utf-8"> <title> ...

  2. WCF简要介绍

    什么是WCF WCF的全称是:Windows Communication Foundation.从本质上来说,它是一套软件开发包,是微软公司推出的符合SOA思想的技术框架.WCF为程序员提供了丰富的功 ...

  3. numpy.flatnonzero():

    numpy.flatnonzero(): 该函数输入一个矩阵,返回扁平化后矩阵中非零元素的位置(index) 这是官方文档给出的用法,非常正规,输入一个矩阵,返回了其中非零元素的位置. 1 >& ...

  4. Go之路之go语言结构

    Go Hello World 实例 package main //定义了包名,必须在源文件中非注释的第一行指名这个文件属于哪个包,每个Go应用程序都包含一个名为main的包 import " ...

  5. SSM11-Redis---jedis的使用方法以及缓存同步

    1. Jedis 需要把jedis依赖的jar包添加到工程中.Maven工程中需要把jedis的坐标添加到依赖. 推荐添加到服务层.E3-content-Service工程中. 1.1. 连接单机版 ...

  6. random模块&hashlib模块

    random模块1.random.randrange(1, 10):返回1-10之间的一个随机数,不包括102.random.randint(1,10):返回1-10之间的一个随机数,包括103.ra ...

  7. c#的DateTime的各种字符串格式

    今天看到工程里有关DateTime的有关知识,之前了解一些用法,比如怎么获取年月日,当前系统时间等等,但是,感觉还是有好多不知道,于是上网搜罗了一下,找到很多有关知识,现在与大家分享下:     Da ...

  8. 前后端分离后API交互如何保证数据安全性

    前后端分离后API交互如何保证数据安全性? 一.前言 前后端分离的开发方式,我们以接口为标准来进行推动,定义好接口,各自开发自己的功能,最后进行联调整合.无论是开发原生的APP还是webapp还是PC ...

  9. 想真正了解JAVA设计模式看着一篇就够了。 详解+代码实例

    Java 设计模式   设计模式是对大家实际工作中写的各种代码进行高层次抽象的总结 设计模式分为 23 种经典的模式,根据用途我们又可以分为三大类.分别是创建型模式.结构型模式和行为型模式 列举几种设 ...

  10. python无法启动火狐浏览器且报错“selenium.common.exceptions.WebDriverException: Message: Unable to find a matching set of capabilities”

    安装了python2,使用pip安装了selenium,但是在使用时,报了“selenium.common.exceptions.WebDriverException: Message: 'gecko ...