linux python pymysql,Python之pymysql的使用

在Python3.x中,可以使用pymysql来MySQL数据库的连接,并实现数据库的各种操作,本次博客主要介绍了pymysql的安装和使用方法。

PyMySQL的安装

一、.windows上的安装方法:

在python3.6中,自带pip3,所以在python3中可以直接使用pip3去安装所需的模块:

pip3 install pymysql -i https://pypi.douban.com/simple

二、.linux下安装方法:

1.tar包下载及解压

下载tar包wget https://pypi.python.org/packages/29/f8/919a28976bf0557b7819fd6935bfd839118aff913407ca58346e14fa6c86/PyMySQL-0.7.11.tar.gz#md5=167f28514f4c20cbc6b1ddf831ade772

解压并展开tar包tar xf PyMySQL-0.7.11.tar.gz

2.安装

[root@localhost PyMySQL-0.7.11]# python36 setup.py install

数据库的连接

本次测试创建的数据及表:

#创建数据库及表,然后插入数据

mysql> create databasedbforpymysql;

mysql> create table userinfo(id int not null auto_increment primary key,username varchar(10),passwd varchar(10))engine=innodb default charset=utf8;

mysql> insert into userinfo(username,passwd) values('frank','123'),('rose','321'),('jeff',666);

#查看表内容

mysql> select * fromuserinfo;+----+----------+--------+

| id | username | passwd |

+----+----------+--------+

| 1 | frank | 123 |

| 2 | rose | 321 |

| 3 | jeff | 666 |

+----+----------+--------+

3 rows in set (0.00 sec)

连接数据库:

importpymysql#连接数据库

db = pymysql.connect("localhost","root","LBLB1212@@","dbforpymysql")#使用cursor()方法创建一个游标对象

cursor =db.cursor()#使用execute()方法执行SQL语句

cursor.execute("SELECT * FROM userinfo")#使用fetall()获取全部数据

data =cursor.fetchall()#打印获取到的数据

print(data)#关闭游标和数据库的连接

cursor.close()

db.close()#运行结果

((1, 'frank', '123'), (2, 'rose', '321'), (3, 'jeff', '666'))

要完成一个MySQL数据的连接,在connect中可以接受以下参数:

b62e9cb9ce2a20846d698e21639529c8.gif

b7de5d75b099c9b746fca4a4179c3c5a.gif

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 serveris 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 interfacefromwhich to connect to the host. Argument can be

a hostnameor 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 parametersfromunder the [client] section.

conv:

Conversion dictionary to use instead of the default one.

Thisis used to provide custom marshalling andunmarshaling of types.

See converters.

use_unicode:

Whetheror notto default to unicode strings.

This option defaults to trueforPy3k.

client_flag: Custom flags to send to MySQL. Find potential valuesinconstants.CLIENT.

cursorclass: Custom cursorclassto use.

init_command: Initial SQL statement to run when connectionisestablished.

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 notsupported.

read_default_group: Group to readfrom inthe 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 serverinbytes. (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 aclassthat processes that plugin.

Theclasswill take the Connection object as the argument to the constructor.

Theclassneeds 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 fromthe user. (experimental)

db: Aliasfor database. (forcompatibility to MySQLdb)

passwd: Aliasfor password. (for compatibility to MySQLdb)

参数

cursor其实是调用了cursors模块下的Cursor的类,这个模块主要的作用就是用来和数据库交互的,当你实例化了一个对象的时候,你就可以调用对象下面的各种绑定方法:

b62e9cb9ce2a20846d698e21639529c8.gif

b7de5d75b099c9b746fca4a4179c3c5a.gif

classCursor(object):"""This is the object you use to interact with the database."""

defclose(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."""

defexecutemany(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()."""

deffetchone(self):"""Fetch the next row"""

def fetchmany(self, size=None):"""Fetch several rows"""

deffetchall(self):"""Fetch all the rows"""......

一些绑定方法

数据库操作

一、数据库增删改操作

commit()方法:在数据库里增、删、改的时候,必须要进行提交,否则插入的数据不生效。

importpymysql

config={"host":"127.0.0.1","user":"root","password":"LBLB1212@@","database":"dbforpymysql"}

db= pymysql.connect(**config)

cursor=db.cursor()

sql= "INSERT INTO userinfo(username,passwd) VALUES('jack','123')"cursor.execute(sql)

db.commit()#提交数据

cursor.close()

db.close()

或者在execute提供插入的数据importpymysql

config={"host":"127.0.0.1","user":"root","password":"LBLB1212@@","database":"dbforpymysql"}

db= pymysql.connect(**config)

cursor=db.cursor()

sql= "INSERT INTO userinfo(username,passwd) VALUES(%s,%s)"cursor.execute(sql,("bob","123"))

db.commit()#提交数据

cursor.close()

db.close()

小知识点,mysql的注入问题:

b7de5d75b099c9b746fca4a4179c3c5a.gif

在mysql中使用"--"代表注释,比如现在来实现一个用户登录的小程序:

用户名和密码都存在表userinfo中,表内容如下:

mysql> select * fromuserinfo;+----+----------+--------+

| id | username | passwd |

+----+----------+--------+

| 1 | frank | 123 |

| 2 | rose | 321 |

| 3 | jeff | 666 |

+----+----------+--------+

3 rows in set (0.00sec)

小程序代码如下:importpymysql

user= input("username:")

pwd= input("password:")

config={"host":"127.0.0.1","user":"root","password":"LBLB1212@@","database":"dbforpymysql"}

db= pymysql.connect(**config)

cursor= db.cursor(cursor=pymysql.cursors.DictCursor)

sql= "select * from userinfo where username='%s' and passwd='%s'" %(user,pwd)

result=cursor.execute(sql)

cursor.close()

db.close()ifresult:print('登录成功')else:print('登录失败')#正确登录的运行结果

username:frank

password:123result:1登录成功#错误登录的运行结果

username:frank

password:1231231result: 0

登录失败

看起来没有什么问题,但是试试下面的方式吧----------------------------------------------username:'or 1=1 --

password:123result:3登录成功----------------------------------------------咦~也登录成功了.

为什么呢?可以看一下现在的执行的sql语句:

select* from userinfo where username='' or 1=1 -- 'and passwd='123'这里--后面的会被注释,所以where一定会成功,这里等于查看了所有行的内容,返回值也不等于0,所以就登录成功了。

解决方法就是将变量或者实参直接写到execute中即可:

result=cursor.execute(sql,(user,pwd))

在键入类似'or 1=1 -- 的时候就不会登录成功了。

MySQL的注入问题

executemany():用来同时插入多条数据:

importpymysql

config={"host":"127.0.0.1","user":"root","password":"LBLB1212@@","database":"dbforpymysql"}

db= pymysql.connect(**config)

cursor=db.cursor()

sql= "INSERT INTO userinfo(username,passwd) VALUES(%s,%s)"cursor.executemany(sql,[("tom","123"),("alex",'321')])

db.commit()#提交数据

cursor.close()

db.close()

execute()和executemany()都会返回受影响的行数:

sql = "delete from userinfo where username=%s"res= cursor.executemany(sql,("jack",))print("res=",res)#运行结果

res= 1

当表中有自增的主键的时候,可以使用lastrowid来获取最后一次自增的ID:

importpymysql

config={"host":"127.0.0.1","user":"root","password":"LBLB1212@@","database":"dbforpymysql"}

db= pymysql.connect(**config)

cursor=db.cursor()

sql= "INSERT INTO userinfo(username,passwd) VALUES(%s,%s)"cursor.execute(sql,("zed","123"))print("the last rowid is",cursor.lastrowid)

db.commit()#提交数据

cursor.close()

db.close()#运行结果

the last rowid is 10

二、数据库的查询操作

这里主要介绍三个绑定方法:

fetchone():获取下一行数据,第一次为首行;

fetchall():获取所有行数据源

fetchmany(4):获取下4行数据

先来查看表的内容:

mysql> select * fromuserinfo;+----+----------+--------+

| id | username | passwd |

+----+----------+--------+

| 1 | frank | 123 |

| 2 | rose | 321 |

| 3 | jeff | 666 |

| 5 | bob | 123 |

| 8 | jack | 123 |

| 10 | zed | 123 |

+----+----------+--------+

6 rows in set (0.00 sec)

使用fetchone():

importpymysql

config={"host":"127.0.0.1","user":"root","password":"LBLB1212@@","database":"dbforpymysql"}

db= pymysql.connect(**config)

cursor=db.cursor()

sql= "SELECT * FROM userinfo"cursor.execute(sql)

res= cursor.fetchone() #第一次执行

print(res)

res= cursor.fetchone() #第二次执行

print(res)

cursor.close()

db.close()#运行结果

(1, 'frank', '123')

(2, 'rose', '321')

使用fetchall():

importpymysql

config={"host":"127.0.0.1","user":"root","password":"LBLB1212@@","database":"dbforpymysql"}

db= pymysql.connect(**config)

cursor=db.cursor()

sql= "SELECT * FROM userinfo"cursor.execute(sql)

res= cursor.fetchall() #第一次执行

print(res)

res= cursor.fetchall() #第二次执行

print(res)

cursor.close()

db.close()#运行结果

((1, 'frank', '123'), (2, 'rose', '321'), (3, 'jeff', '666'), (5, 'bob', '123'), (8, 'jack', '123'), (10, 'zed', '123'))

()

可以看到,第二次获取的时候,什么数据都没有获取到,这个类似于文件的读取操作。

默认情况下,我们获取到的返回值是元组,只能看到每行的数据,却不知道每一列代表的是什么,这个时候可以使用以下方式来返回字典,每一行的数据都会生成一个字典:

cursor = db.cursor(cursor=pymysql.cursors.DictCursor) #在实例化的时候,将属性cursor设置为pymysql.cursors.DictCursor

使用fetchall获取所有行的数据,每一行都被生成一个字典放在列表里面:

importpymysql

config={"host":"127.0.0.1","user":"root","password":"LBLB1212@@","database":"dbforpymysql"}

db= pymysql.connect(**config)

cursor= db.cursor(cursor=pymysql.cursors.DictCursor)

sql= "SELECT * FROM userinfo"cursor.execute(sql)

res=cursor.fetchall()print(res)

cursor.close()

db.close()#运行结果

[{'id': 1, 'username': 'frank', 'passwd': '123'}, {'id': 2, 'username': 'rose', 'passwd': '321'}, {'id': 3, 'username': 'jeff', 'passwd': '666'}, {'id': 5, 'username': 'bob', 'passwd': '123'}, {'id': 8, 'username': 'jack', 'passwd': '123'}, {'id': 10, 'username': 'zed', 'passwd': '123'}]

这样获取到的内容就能够容易被理解和使用了!

在获取行数据的时候,可以理解开始的时候,有一个行指针指着第一行的上方,获取一行,它就向下移动一行,所以当行指针到最后一行的时候,就不能再获取到行的内容,所以我们可以使用如下方法来移动行指针:

cursor.scroll(1,mode='relative') #相对当前位置移动

cursor.scroll(2,mode='absolute') #相对绝对位置移动

第一个值为移动的行数,整数为向下移动,负数为向上移动,mode指定了是相对当前位置移动,还是相对于首行移动

例如:

sql = "SELECT * FROM userinfo"cursor.execute(sql)

res=cursor.fetchall()print(res)

cursor.scroll(0,mode='absolute') #相对首行移动了0,就是把行指针移动到了首行

res = cursor.fetchall() #第二次获取到的内容

print(res)#运行结果

[{'id': 1, 'username': 'frank', 'passwd': '123'}, {'id': 2, 'username': 'rose', 'passwd': '321'}, {'id': 3, 'username': 'jeff', 'passwd': '666'}, {'id': 5, 'username': 'bob', 'passwd': '123'}, {'id': 8, 'username': 'jack', 'passwd': '123'}, {'id': 10, 'username': 'zed', 'passwd': '123'}]

[{'id': 1, 'username': 'frank', 'passwd': '123'}, {'id': 2, 'username': 'rose', 'passwd': '321'}, {'id': 3, 'username': 'jeff', 'passwd': '666'}, {'id': 5, 'username': 'bob', 'passwd': '123'}, {'id': 8, 'username': 'jack', 'passwd': '123'}, {'id': 10, 'username': 'zed', 'passwd': '123'}]

上下文管理器

在python的文件操作中支持上下文管理器,在操作数据库的时候也可以使用:

importpymysql

config={"host":"127.0.0.1","user":"root","password":"LBLB1212@@","database":"dbforpymysql"}

db= pymysql.connect(**config)

with db.cursor(cursor=pymysql.cursors.DictCursor) as cursor: #获取数据库连接的对象

sql = "SELECT * FROM userinfo"cursor.execute(sql)

res=cursor.fetchone()print(res)

cursor.scroll(2,mode='relative')

res=cursor.fetchone()print(res)

cursor.close()

db.close()#运行结果

{'id': 1, 'username': 'frank', 'passwd': '123'}

{'id': 5, 'username': 'bob', 'passwd': '123'}

上下文管理器可以使代码的可读性更强。

0b1331709591d260c1c78e86d0c51c18.png

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/405656.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

树莓派静态IP配置方法

一、网络接口文件 配置静态IP有个好处在于每次的访问IP是固定的,比如用到的samba服务器共享文件时可以不改动网络地址。树莓派网络接口在/etc/network/interfaces 文件中进行配置,打开该文件:sudo vi /etc/network/interfaces 可以看到第四行…

带可变参数的宏函数和普通函数实现

From: http://www.vimer.cn/2010/03/cc%E5%AE%8F%E5%AE%9A%E4%B9%89%E7%9A%84%E5%8F%AF%E5%8F%98%E5%8F%82%E6%95%B0.html 编写代码的过程中,经常会输出一些调试信息到屏幕上,一般会调用printf这类的函数。 但是当调试解决之后,我们需要手工将…

SAP 免费赠与客户货物的销项税处理

免费赠与客户货物的销项税处理 如果免费赠与客户货物却要体现销项税,如何处理?在实际业务中因为免费货物是不免税的。所以大家总是以为使用0费用解决但是有一种情况是存在于视同销售。 即D:销售费用 C:销项税 SAP中的处理逻…

前端小知识点(2):普通字符串和new String有什么区别

目录 一、其实不仅字符串 二、那么到底为什么? 三、代码案例 四、运行结果 一、其实不仅字符串 var str abc; typeof str > string //他不是对象,可以有方法或者属性 var num 123; //他不是对象,可以有方法或者属性 typeof num …

linux更新命令yum,Linux中升级更新命令yum upgrade和yum update的区别

Linux中升级更新命令yum upgrade和yum update的区别更新时间:2019-10-31 17:21最满意答案Linux升级命令有两个分别是yum upgrade和yum update, 这个两个命令是有区别的:复制代码代码如下:yum -y update升级所有包同时也升级软件和系统内核复制代码代码如下:yum -y u…

Linux 管理登陆的用户/查看/剔除

Linux是多用户操作系统,支持多用户同时在线,支持对登陆用户的管理:查看与剔除等。 一、查看在线用户命令 命令: w 二、查看登录记录命令 命令 last 三、剔除在线用户命令 命令:sudo pkill -kill -t usr 四、pkill…

Windows下 maven3.0.4的安装步骤+maven配置本地仓库

简单讲下maven的安装步骤: 1.在安装maven之前,先确保已经安装JDK1.6及以上版本,并且配置好环境变量。 2.下载maven3,最新版本是Maven3.0.4 ,下载地址:http://maven.apache.org/download.html 下载apache…

C语言日志操作类实例

包含三个主要的文件&#xff1a;joefunction.h(c), m.c(主函数文件) 1. m.c #include <stdio.h> #include <string.h> #include <time.h> #include "joefunction.h"extern FILE *g_logFile;int main(int argc, char *argv[]) {char temp[16] {0}…

ESX与ESXi管理员必备25个命令

ESX与ESXi管理员必备25个命令VMware ESX和ESXi命令这些VMware ESX和ESXi的命令可以运行在ESX服务控制台&#xff08;本地或远程使用Secure Shell&#xff09;或RCLI&#xff08;在VMware Infrastructure 3&#xff09;和vSphere CLI的&#xff08;在vSphere&#xff09;。在RCL…

前端小知识点(3):JavaScript 单线程

目录 一、为什么 JavaScript 是单线程&#xff1f; 二、JavaScript是单线程&#xff0c;怎样执行异步的代码&#xff1f; 三、事件循环机制 四、代码1 五、结果1 六、代码2 七、结果2 一、为什么 JavaScript 是单线程&#xff1f; JavaScript 语言的一大特点就是单线程…

Linux安装samba的过程,Samba安装全过程

对于linux与windows共享&#xff0c;和平共处&#xff0c;我们可以用Samba软件Samba是一套免费的开源软件&#xff0c;可以在linux或其他类unix操作系统上实现windows域控制器&#xff0c;文件服务&#xff0c;打印服务等。Samba实现了windows系统所使用的核心网络协议&#xf…

树莓派UART串口编程--使用wiringPi库-C开发【2-修改驱动】

一、前言 上一篇博文记录了使用wiringPi提供的串口驱动wiringSerial.c wiringSerial.h&#xff0c;并基于该驱动对串口进行简单的通信&#xff0c;测试中发现该串口的驱动比较简单&#xff0c;接收数据会存在分包的现象&#xff0c;另外一点是串口配置只提供了波特率参数配置&…

《软件开发计划》

校友聊项目开发计划书 项目名称&#xff1a;校友聊 1.引言 1.1编写目的 编写本文档的目的是为了校园内网的用户使用本软件进行文字&#xff0c;视频聊天&#xff0c;而不耗费内网的外网的流量。 1.2背景 基于校园内网用户对流量的强大需求&#xff0c;以及考虑到其中一些特殊用…

【转】全面理解javascript的arguments,callee,caller,call,apply概念(修改版)

(注&#xff1a;在看到大家如此关注JS里头的这几个对象&#xff0c;我试着把原文再修改一下&#xff0c;力求能再详细的阐明个中意义 2007-05-21&#xff09;在提到上述的概念之前&#xff0c;首先想说说javascript中函数的隐含参数&#xff1a;arguments Arguments 该对象代表…

windows延缓写入失败相关问题解决办法

From: http://www.ggsafe.com/news/1324547234222.shtml 我们在使用电脑时&#xff0c;有时在不正常关机后电脑会出现这样那样的问题。windows延缓写入失败就是其中一个&#xff0c;很多网友在互联网上发帖求助windows延缓写入失败怎么办&#xff0c;出现这种情况一般都是由于电…

wince linux 性能,wince remote call profiler(性能分析)

如何使用1 建立工程,CPU类型必须于目标机型一致如ARMV4I,所以选择WCE Application,然后选择empty project2 project settings 中,link页,Object/library modules中添加 cecap.lib(前面有空格),Ingore libraries中添加,libc.lib(前面有逗号).C/C页Project Options最后添加 /call…

前端小知识点(4):JS 运行机制和存储

目录 被忽视的内存管理 JS工作原理 JS代码如何运行 JavaScript内存的生命周期 栈内存、堆内存 代码案例 运行结果 被忽视的内存管理 JavaScript不像C、C等语言——程序员必须通过调用内存管理接口&#xff0c;比如 malloc()和free()&#xff0c;自己手动分配和释放内存。…

201506230818_《JavaScript权威指南(第六版)——callee和caller、对象属性用作实参、自定义函数属性》(P175-180)...

1. callee 正在执行的函数。使用方法&#xff1a;arguments.callee... caller 正在调用执行函数的函数。 2.对象属性用作实参&#xff0c;形如&#xff1a;function fn(arg) { var arg.name name || Josn, arg.age age || 60 , ... } 3. 在传入实参时候&#xff0c;宁愿在检查…

VIM选择文本块

From: http://hi.baidu.com/mykledge/blog/item/d42e4d63f57232d48cb10d6c.html 在正常模式下&#xff08;按ESC进入&#xff09;按键v进入可视化模式&#xff0c;然后按键盘左右键或h,l键即可实现文本的选择。 其它相关命令&#xff1a; v&#xff1a;按字符选择。经常使用的模…

Linux ps aux查看进程

一、ps 命令 ps 是Process Status的缩写&#xff0c;用于查看进程状态&#xff0c;ps 可以显示linux系统的所有进程信息。 用法&#xff1a; ps a 显示现行终端机下的所有程序&#xff0c;包括其他用户的程序。ps -A 显示所有程序。 ps c 列出程序时&#xff0c;显示每个程序…