mysql的基本使用及与python交互

一、mysql服务端安装

1、安装

# mac下
brew install mysql

2、启动

mysql.server start

3、初始化

任意位置执行

mysql_secure_installation
Securing the MySQL server deployment.

 

Connecting to MySQL using a blank password.

 

VALIDATE PASSWORD COMPONENT can be used to test passwords

and improve security. It checks the strength of password

and allows the users to set only those passwords which are

secure enough. Would you like to setup VALIDATE PASSWORD component?

 

Press y|Y for Yes, any other key for No: n    // 这个选yes的话密码长度就必须要设置为8位以上,但我只想要6位的

Please set the password for root here.

New password:

Re-enter new password:

By default, a MySQL installation has an anonymous user,

allowing anyone to log into MySQL without having to have

a user account created for them. This is intended only for

testing, and to make the installation go a bit smoother.

You should remove them before moving into a production

environment.

 

Remove anonymous users? (Press y|Y for Yes, any other key for No) : y          // 移除不用密码的那个账户

Success.

 

Normally, root should only be allowed to connect from

'localhost'. This ensures that someone cannot guess at

the root password from the network.

 

Disallow root login remotely? (Press y|Y for Yes, any other key for No) : n      //不接受root远程登录账号

 

... skipping.

By default, MySQL comes with a database named 'test' that

anyone can access. This is also intended only for testing,

and should be removed before moving into a production

environment.

 

 

Remove test database and access to it? (Press y|Y for Yes, any other key for No) : y     //删除text数据库

- Dropping test database...

Success.

 

- Removing privileges on test database...

Success.

 

Reloading the privilege tables will ensure that all changes

made so far will take effect immediately.

 

Reload privilege tables now? (Press y|Y for Yes, any other key for No) : y

Success.

 

All done!

3、查看是否启动

mysql.server status 或者 ps -ef|grep mysqld

4、停止服务

mysql.server stop

5、重启服务

mysql.server restart

二、客户端安装

1、可视化mysql客户端

可以到[Navicat官网](https://www.navicat.com.cn/)下载安装.
mac推荐Selquel pro 

2、命令行客户端安装

2.1 安装

brew install mysql-client

2.2 查看连接命令

mysql --help

2.3 连接数据库命令

mysql -u root -p # 回车后输入密码
mysql -u root -p密码 # 直接登录

2.4 退出

exit或者quit或者ctrl+d

三、数据完整性

一个数据库就是一个完整的业务单元,可以包含多张表,数据被存储在表中
在表中为了更加准确的存储数据,保证数据的正确有效,可以在创建表的时候,为表添加一些强制性的验证,包括数据字段的类型、约束
数据类型
可以通过查看帮助文档查阅所有支持的数据类型
使用数据类型的原则是:够用就行,尽量使用取值范围小的,而不用大的,这样可以更多的节省存储空间
常用数据类型如下:
整数:int,bit
小数:decimal
字符串:varchar,char
日期时间: date, time, datetime
枚举类型(enum)
特别说明的类型如下:
decimal表示浮点数,如decimal(5,2)表示共存5位数,小数占2位
char表示固定长度的字符串,如char(3),如果填充’ab’时会补一个空格为’ab ’
varchar表示可变长度的字符串,如varchar(3),填充’ab’时就会存储’ab’
字符串text表示存储大文本,当字符大于4000时推荐使用
对于图片、音频、视频等文件,不存储在数据库中,而是上传到某个服务器上,然后在表中存储这个文件的保存路径
更全的数据类型可以参考http://blog.csdn.net/anxpp/article/details/51284106
约束
主键primary key:物理上存储的顺序
非空not null:此字段不允许填写空值
惟一unique:此字段的值不允许重复
默认default:当不填写此值时会使用默认值,如果填写时以填写为准
外键foreign key:对关系字段进行约束,当为关系字段填写值时,会到关联的表中查询此值是否存在,如果存在则填写成功,如果不存在则填写失败并抛出异常
说明:虽然外键约束可以保证数据的有效性,但是在进行数据的crud(增加、修改、删除、查询)时,都会降低数据库的性能,所以不推荐使用,那么数据的有效性怎么保证呢?答:可以在逻辑层进行控制
数值类型(常用)

类型 字节大小 有符号范围(Signed) 无符号范围(Unsigned)
TINYINT 1 -128 ~ 127 0 ~ 255
SMALLINT 2 -32768 ~ 32767 0 ~ 65535
MEDIUMINT 3 -8388608 ~ 8388607 0 ~ 16777215
INT/INTEGER 4 -2147483648 ~2147483647 0 ~ 4294967295
BIGINT 8 -9223372036854775808 ~ 9223372036854775807 0 ~ 18446744073709551615
字符串

类型 字节大小 示例
CHAR 0-255 类型:char(3) 输入 ‘ab’, 实际存储为’ab ‘, 输入’abcd’ 实际存储为 ‘abc’
VARCHAR 0-255 类型:varchar(3) 输 ‘ab’,实际存储为’ab’, 输入’abcd’,实际存储为’abc’
TEXT 0-65535 大文本
日期时间类型

类型 字节大小 示例
DATE 4 ‘2020-01-01’
TIME 3 ‘12:29:59’
DATETIME 8 ‘2020-01-01 12:29:59’
YEAR 1 ‘2017’
TIMESTAMP 4 ‘1970-01-01 00:00:01’ UTC ~ ‘2038-01-01 00:00:01’ UTC

四、数据库操作

1. 数据库操作

1.1查看所有数据库

show databases;

1.2使用数据库

use 数据库名;

1.3查看当前使用的数据库

select database();

1.4 创建数据库

create database 数据库名 charset=utf8;

1.5删除数据库

drop database 数据库名

2、数据表操作

-- 数据表的操作

    -- 查看当前数据库中所有表
    show tables;
    

    -- 创建表
    -- auto_increment表示自动增长
    -- not null 表示不能为空
    -- primary key 表示主键
    -- default 默认值
    -- create table 数据表名字 (字段 类型 约束[, 字段 类型 约束]);
    create table xxxxx(id int, name varchar(30));
    create table yyyyy(id int primary key not null auto_increment, name varchar(30));
    create table zzzzz(
        id int primary key not null auto_increment,
        name varchar(30)
    );

    -- 查看表结构
    -- desc 数据表的名字;
    desc xxxxx;

    -- 创建students表(id、name、age、high、gender、cls_id)
    create table students(
        id int unsigned not null auto_increment primary key,
        name varchar(30),
        age tinyint unsigned default 0,
        high decimal(5,2),
        gender enum("男", "女", "中性", "保密") default "保密",
        cls_id int unsigned
    );

    insert into students values(0, "老王", 18, 188.88, "男", 0);
    select * from students;

    -- 创建classes表(id、name)
    create table classes(
        id int unsigned not null auto_increment primary key,
        name varchar(30)
    );

    insert into classes values(0, "python04大神");
    select * from classes;

    -- 查看表的创建语句
    -- show create table 表名字;
    show create table students;


    -- 修改表-添加字段
    -- alter table 表名 add 列名 类型;
    alter table students add birthday datetime;
    

    -- 修改表-修改字段:不重命名版
    -- alter table 表名 modify 列名 类型及约束;
    alter table students modify birthday date;


    -- 修改表-修改字段:重命名版
    -- alter table 表名 change 原名 新名 类型及约束;
    alter table students change birthday birth date default "2000-01-01";


    -- 修改表-删除字段
    -- alter table 表名 drop 列名;
    alter table students drop high;


    -- 删除表
    -- drop table 表名;
    -- drop database 数据库;
    -- drop table 数据表;
    drop table xxxxx;

    
-- 增删改查(curd)

    -- 增加
        -- 全列插入
        -- insert [into] 表名 values(...)
        -- 主键字段 可以用 0  null   default 来占位
        -- 向classes表中插入 一个班级
        insert into classes values(0, "菜鸟班");


        +--------+-------------------------------------+------+-----+------------+----------------+
        | Field  | Type                                | Null | Key | Default    | Extra          |
        +--------+-------------------------------------+------+-----+------------+----------------+
        | id     | int(10) unsigned                    | NO   | PRI | NULL       | auto_increment |
        | name   | varchar(30)                         | YES  |     | NULL       |                |
        | age    | tinyint(3) unsigned                 | YES  |     | 0          |                |
        | gender | enum('男','女','中性','保密')       | YES  |     | 保密       |                |
        | cls_id | int(10) unsigned                    | YES  |     | NULL       |                |
        | birth  | date                                | YES  |     | 2000-01-01 |                |
        +--------+-------------------------------------+------+-----+------------+----------------+

        -- 向students表插入 一个学生信息
        insert into students values(0, "小李飞刀", 20, "女", 1, "1990-01-01");
        insert into students values(null, "小李飞刀", 20, "女", 1, "1990-01-01");
        insert into students values(default, "小李飞刀", 20, "女", 1, "1990-01-01");

        -- 失败
        -- insert into students values(default, "小李飞刀", 20, "第4性别", 1, "1990-02-01");

        -- 枚举中 的 下标从1 开始 1---“男” 2--->"女"....
        insert into students values(default, "小李飞刀", 20, 1, 1, "1990-02-01");

        -- 部分插入
        -- insert into 表名(列1,...) values(值1,...)
        insert into students (name, gender) values ("小乔", 2);


        -- 多行插入
        insert into students (name, gender) values ("大乔", 2),("貂蝉", 2);
        insert into students values(default, "西施", 20, "女", 1, "1990-01-01"), (default, "王昭君", 20, "女", 1, "1990-01-01");


    -- 修改
    -- update 表名 set 列1=值1,列2=值2... where 条件;
        update students set gender=1; -- 全部都改
        update students set gender=1 where name="小李飞刀"; -- 只要name是小李飞刀的 全部的修改
        update students set gender=1 where id=3; -- 只要id为3的 进行修改
        update students set age=22, gender=1 where id=3; -- 只要id为3的 进行修改
    
    -- 查询基本使用
        -- 查询所有列
        -- select * from 表名;
        select * from students;

        ---定条件查询
        select * from students where name="小李飞刀"; -- 查询 name为小李飞刀的所有信息
        select * from students where id>3; -- 查询 name为小李飞刀的所有信息


        -- 查询指定列
        -- select 列1,列2,... from 表名;
        select name,gender from students;


        -- 可以使用as为列或表指定别名
        -- select 字段[as 别名] , 字段[as 别名] from 数据表 where ....;
        select name as 姓名,gender as 性别 from students;


        -- 字段的顺序
        select id as 序号, gender as 性别, name as 姓名 from students;
    -- 数据的准备
	-- 创建一个数据库
	create database python_test charset=utf8;

	-- 使用一个数据库
	use python_test;

	-- 显示使用的当前数据是哪个?
	select database();

	-- 创建一个数据表
	-- students表
	create table students(
	    id int unsigned primary key auto_increment not null,
	    name varchar(20) default '',
	    age tinyint unsigned default 0,
	    height decimal(5,2),
	    gender enum('男','女','中性','保密') default '保密',
	    cls_id int unsigned default 0,
	    is_delete bit default 0
	);

	-- classes表
	create table classes (
	    id int unsigned auto_increment primary key not null,
	    name varchar(30) not null
	);



-- 查询
	-- 查询所有字段
	-- select * from 表名;
	select * from students;
	select * from classes;
	select id, name from classes;

	-- 查询指定字段
	-- select 列1,列2,... from 表名;
	select name, age from students;
	
	-- 使用 as 给字段起别名
	-- select 字段 as 名字.... from 表名;
	select name as 姓名, age as 年龄 from students;

	-- select 表名.字段 .... from 表名;
	select students.name, students.age from students;

	
	-- 可以通过 as 给表起别名
	-- select 别名.字段 .... from 表名 as 别名;
	select students.name, students.age from students;
	select s.name, s.age from students as s;
	-- 失败的select students.name, students.age from students as s;


	-- 消除重复行
	-- distinct 字段
	select distinct gender from students;


-- 条件查询
	-- 比较运算符
		-- select .... from 表名 where .....
		-- >
		-- 查询大于18岁的信息
		select * from students where age>18;
		select id,name,gender from students where age>18;

		-- <
		-- 查询小于18岁的信息
		select * from students where age<18;

		-- >=
		-- <=
		-- 查询小于或者等于18岁的信息

		-- =
		-- 查询年龄为18岁的所有学生的名字
		select * from students where age=18;


		-- != 或者 <>


	-- 逻辑运算符
		-- and
		-- 18到28之间的所以学生信息
		select * from students where age>18 and age<28;
		-- 失败select * from students where age>18 and <28;


		-- 18岁以上的女性
		select * from students where age>18 and gender="女";
		select * from students where age>18 and gender=2;


		-- or
		-- 18以上或者身高查过180(包含)以上
		select * from students where age>18 or height>=180;


		-- not
		-- 不在 18岁以上的女性 这个范围内的信息
		-- select * from students where not age>18 and gender=2;
		select * from students where not (age>18 and gender=2);

		-- 年龄不是小于或者等于18 并且是女性
		select * from students where (not age<=18) and gender=2;


	-- 模糊查询
		-- like 
		-- % 替换1个或者多个
		-- _ 替换1个
		-- 查询姓名中 以 "小" 开始的名字
		select name from students where name="小";
		select name from students where name like "小%";

		-- 查询姓名中 有 "小" 所有的名字
		select name from students where name like "%小%";

		-- 查询有2个字的名字
		select name from students where name like "__";

		-- 查询有3个字的名字
		select name from students where name like "__";

		-- 查询至少有2个字的名字
		select name from students where name like "__%";


		-- rlike 正则
		-- 查询以 周开始的姓名
		select name from students where name rlike "^周.*";

		-- 查询以 周开始、伦结尾的姓名
		select name from students where name rlike "^周.*伦$";


	-- 范围查询
		-- in (1, 3, 8)表示在一个非连续的范围内
		-- 查询 年龄为18、34的姓名
		select name,age from students where age=18 or age=34;
		select name,age from students where age=18 or age=34 or age=12;
		select name,age from students where age in (12, 18, 34);


		
		-- not in 不非连续的范围之内
		-- 年龄不是 18、34岁之间的信息
		select name,age from students where age not in (12, 18, 34);


		-- between ... and ...表示在一个连续的范围内
		-- 查询 年龄在18到34之间的的信息
		select name, age from students where age between 18 and 34;

		
		-- not between ... and ...表示不在一个连续的范围内
		-- 查询 年龄不在在18到34之间的的信息
		select * from students where age not between 18 and 34;
		select * from students where not age between 18 and 34;
		-- 失败的select * from students where age not (between 18 and 34);


	-- 空判断
		-- 判空is null
		-- 查询身高为空的信息
		select * from students where height is null;
		select * from students where height is NULL;
		select * from students where height is Null;

		-- 判非空is not null
		select * from students where height is not null;



-- 排序
	-- order by 字段
	-- asc从小到大排列,即升序
	-- desc从大到小排序,即降序

	-- 查询年龄在18到34岁之间的男性,按照年龄从小到到排序
	select * from students where (age between 18 and 34) and gender=1;
	select * from students where (age between 18 and 34) and gender=1 order by age;
	select * from students where (age between 18 and 34) and gender=1 order by age asc;


	-- 查询年龄在18到34岁之间的女性,身高从高到矮排序
	select * from students where (age between 18 and 34) and gender=2 order by height desc;
	

	-- order by 多个字段
	-- 查询年龄在18到34岁之间的女性,身高从高到矮排序, 如果身高相同的情况下按照年龄从小到大排序
	select * from students where (age between 18 and 34) and gender=2 order by height desc,id desc;


	-- 查询年龄在18到34岁之间的女性,身高从高到矮排序, 如果身高相同的情况下按照年龄从小到大排序,
	-- 如果年龄也相同那么按照id从大到小排序
	select * from students where (age between 18 and 34) and gender=2 order by height desc,age asc,id desc;

	
	-- 按照年龄从小到大、身高从高到矮的排序
	select * from students order by age asc, height desc;


-- 聚合函数
	-- 总数
	-- count
	-- 查询男性有多少人,女性有多少人
	select * from students where gender=1;
	select count(*) from students where gender=1;
	select count(*) as 男性人数 from students where gender=1;
	select count(*) as 女性人数 from students where gender=2;


	-- 最大值
	-- max
	-- 查询最大的年龄
	select age from students;
	select max(age) from students;

	-- 查询女性的最高 身高
	select max(height) from students where gender=2;

	-- 最小值
	-- min

	
	-- 求和
	-- sum
	-- 计算所有人的年龄总和
	select sum(age) from students;

	
	-- 平均值
	-- avg
	-- 计算平均年龄
	select avg(age) from students;


	-- 计算平均年龄 sum(age)/count(*)
	select sum(age)/count(*) from students;


	-- 四舍五入 round(123.23 , 1) 保留1位小数
	-- 计算所有人的平均年龄,保留2位小数
	select round(sum(age)/count(*), 2) from students;
	select round(sum(age)/count(*), 3) from students;

	-- 计算男性的平均身高 保留2位小数
	select round(avg(height), 2) from students where gender=1;
	-- select name, round(avg(height), 2) from students where gender=1;

-- 分组

	-- group by
	-- 按照性别分组,查询所有的性别
	select name from students group by gender;
	select * from students group by gender;
	select gender from students group by gender;
	-- 失败select * from students group by gender;

	-- 计算每种性别中的人数
	select gender,count(*) from students group by gender;


	-- 计算男性的人数
	select gender,count(*) from students where gender=1 group by gender;


	-- group_concat(...)
	-- 查询同种性别中的姓名
 	select gender,group_concat(name) from students where gender=1 group by gender;
 	select gender,group_concat(name, age, id) from students where gender=1 group by gender;
 	select gender,group_concat(name, "_", age, " ", id) from students where gender=1 group by gender;

	-- having
	-- 查询平均年龄超过30岁的性别,以及姓名 having avg(age) > 30
	select gender, group_concat(name),avg(age) from students group by gender having avg(age)>30;
	
	-- 查询每种性别中的人数多于2个的信息
	select gender, group_concat(name) from students group by gender having count(*)>2;



-- 分页
	-- limit start, count

	-- 限制查询出来的数据个数
	select * from students where gender=1 limit 2;

	-- 查询前5个数据
	select * from students limit 0, 5;

	-- 查询id6-10(包含)的书序
	select * from students limit 5, 5;


	-- 每页显示2个,第1个页面
	select * from students limit 0,2;

	-- 每页显示2个,第2个页面
	select * from students limit 2,2;

	-- 每页显示2个,第3个页面
	select * from students limit 4,2;

	-- 每页显示2个,第4个页面
	select * from students limit 6,2; -- -----> limit (第N页-1)*每个的个数, 每页的个数;

	-- 每页显示2个,显示第6页的信息, 按照年龄从小到大排序
	-- 失败select * from students limit 2*(6-1),2;
	-- 失败select * from students limit 10,2 order by age asc;
	select * from students order by age asc limit 10,2;

	select * from students where gender=2 order by height desc limit 0,2;



-- 连接查询
	-- inner join ... on

	-- select ... from 表A inner join 表B;
	select * from students inner join classes;

	-- 查询 有能够对应班级的学生以及班级信息
	select * from students inner join classes on students.cls_id=classes.id;

	-- 按照要求显示姓名、班级
	select students.*, classes.name from students inner join classes on students.cls_id=classes.id;
	select students.name, classes.name from students inner join classes on students.cls_id=classes.id;

	-- 给数据表起名字
	select s.name, c.name from students as s inner join classes as c on s.cls_id=c.id;

	-- 查询 有能够对应班级的学生以及班级信息,显示学生的所有信息,只显示班级名称
	select s.*, c.name from students as s inner join classes as c on s.cls_id=c.id;
	
	-- 在以上的查询中,将班级姓名显示在第1列
	select c.name, s.* from students as s inner join classes as c on s.cls_id=c.id;

	-- 查询 有能够对应班级的学生以及班级信息, 按照班级进行排序
	-- select c.xxx s.xxx from student as s inner join clssses as c on .... order by ....;
	select c.name, s.* from students as s inner join classes as c on s.cls_id=c.id order by c.name;

	-- 当时同一个班级的时候,按照学生的id进行从小到大排序
	select c.name, s.* from students as s inner join classes as c on s.cls_id=c.id order by c.name,s.id;

	-- left join
	-- 查询每位学生对应的班级信息
	select * from students as s left join classes as c on s.cls_id=c.id;

	-- 查询没有对应班级信息的学生
	-- select ... from xxx as s left join xxx as c on..... where .....
	-- select ... from xxx as s left join xxx as c on..... having .....
	select * from students as s left join classes as c on s.cls_id=c.id having c.id is null;
	select * from students as s left join classes as c on s.cls_id=c.id where c.id is null;

	-- right join   on
	-- 将数据表名字互换位置,用left join完成

-- 自关联
	-- 建表语句
	链接: https://pan.baidu.com/s/1VkKuwef5wPAuLHtF5OapDg  密码: ms8k
	-- 查询所有省份
	select * from sys_area where area_parent_id=0;

	-- 查询出甘肃省有哪些市
	select city.area_name  from sys_area as province inner join sys_area as city on province.id=city.area_parent_id where province.area_name="甘肃省";
	-- 查询出庆阳市有哪些县城
select area.area_name from sys_area as city inner join sys_area as area on city.id=area.area_parent_id where city.area_name="庆阳市";
	select * from sys_area where area_parent_id=(select id from sys_area where area_name="庆阳市");


-- 子查询
	-- 标量子查询
	-- 查询出高于平均身高的信息

	-- 查询最高的男生信息
	select * from students where height = 188;
	select * from students where height = (select max(height) from students);

	-- 列级子查询
	-- 查询学生的班级号能够对应的学生信息
	-- select * from students where cls_id in (select id from classes);


    -- 删除
        -- 物理删除
        -- delete from 表名 where 条件
        delete from students; -- 整个数据表中的所有数据全部删除
        delete from students where name="小李飞刀";

        -- 逻辑删除
        -- 用一个字段来表示 这条信息是否已经不能再使用了
        -- 给students表添加一个is_delete字段 bit 类型
        alter table students add is_delete bit default 0;
        update students set is_delete=1 where id=6;

4、备份与恢复

4.1备份

mysqldump –uroot –p 数据库名 > python.sql;

# 按提示输入mysql的密码

4.2恢复

mysql -uroot –p 新数据库名 < python.sql

# 根据提示输入mysql密码

五、与python交互

1、参数及使用方法

引入模块
在py文件中引入pymysql模块
from pymysql import *
Connection 对象
用于建立与数据库的连接

创建对象:调用connect()方法

conn=connect(参数列表)
参数host:连接的mysql主机,如果本机是’localhost’
参数port:连接的mysql主机的端口,默认是3306
参数database:数据库的名称
参数user:连接的用户名
参数password:连接的密码
参数charset:通信采用的编码方式,推荐使用utf8
对象的方法
close()关闭连接
commit()提交
cursor()返回Cursor对象,用于执行sql语句并获得结果
Cursor对象
用于执行sql语句,使用频度最高的语句为select、insert、update、delete
获取Cursor对象:调用Connection对象的cursor()方法
cs1=conn.cursor()
对象的方法
close()关闭
execute(operation [, parameters ])执行语句,返回受影响的行数,主要用于执行insert、update、delete语句,也可以执行create、alter、drop等语句
fetchone()执行查询语句时,获取查询结果集的第一个行数据,返回一个元组
fetchall()执行查询时,获取结果集的所有行,一行构成一个元组,再将这些元组装入一个元组返回
对象的属性
rowcount只读属性,表示最近一次execute()执行后受影响的行数
connection获得当前连接对象

from pymysql import connect


class Areas(object):
    def __init__(self):
        self.conn = connect(host='localhost', port=3306, user='root', password='999999',
                            database='python', charset='utf8')
        self.curs = self.conn.cursor()

    def __del__(self):
        self.curs.close()
        self.conn.close()

    @staticmethod
    def menu():
        print("*"*50)
        print("查所有市/区县请输入1")
        print("查省份信息请输入2")
        print("插入信息请输入3")
        print("删除数据请输入4")
        print("*" * 50)
        return input("请输入:")

    # 插入数据
    def insert_area(self):
		pass

    # 数据为空,是否要插入数据
    def select_empty(self):
        user_inout = input("您查询的数据为空,是否要补充数据,Y or N:")
        if user_inout == "Y":
            self.insert_area()

    # 通过省份/市区名称查所在省或者市下边的区县
    def show_area(self):
        name = input("请输入所查省份/市名称?")
        sql = 'select city.area_name from areas as province inner join areas as city ' \
              'on province.id=city.area_parent_id where province.area_name=%s;'
        self.curs.execute(sql, name)
        ret = self.curs.fetchall()
        if ret:
            return ret
        else:
            self.select_empty()

    # 通过市区名称查所在省份信息
    def show_province(self):
        name = input("请输入所查市/区名称:")
        sql = 'select province.area_name from areas as city inner join areas province ' \
              'on city.area_parent_id=province.id where city.area_name=%s'
        self.curs.execute(sql, name)
        ret = self.curs.fetchall()
        if ret:
            return ret
        else:
            self.select_empty()

    # 更新信息
    def update_area(self):
        pass

    # 删除信息
    def del_area(self):
        pass

    def run(self):
        num = self.menu()
        if num == "1":
            for i in self.show_area():
                print(i)
        elif num == "2":
            for i in self.show_province():
                print(i)
        else:
            print("输入有误")


a = Areas()
a.run()

2、使用参数化防止sql注入

sql语句的参数化,可以有效防止sql注入
注意:此处不同于python的字符串格式化,全部使用%s占位

from pymysql import *

def main():

    find_name = input("请输入物品名称:")

    # 创建Connection连接
    conn = connect(host='localhost',port=3306,user='root',password='mysql',database='jing_dong',charset='utf8')
    # 获得Cursor对象
    cs1 = conn.cursor()


    # # 非安全的方式
    # # 输入 " or 1=1 or "   (双引号也要输入)
    # sql = 'select * from goods where name="%s"' % find_name
    # print("""sql===>%s<====""" % sql)
    # # 执行select语句,并返回受影响的行数:查询所有数据
    # count = cs1.execute(sql)

    # 安全的方式
    # 构造参数列表
    params = [find_name]
    # 执行select语句,并返回受影响的行数:查询所有数据
    count = cs1.execute('select * from goods where name=%s', params)
    # 注意:
    # 如果要是有多个参数,需要进行参数化
    # 那么params = [数值1, 数值2....],此时sql语句中有多个%s即可 

    # 打印受影响的行数
    print(count)
    # 获取查询的结果
    # result = cs1.fetchone()
    result = cs1.fetchall()
    # 打印查询的结果
    print(result)
    # 关闭Cursor对象
    cs1.close()
    # 关闭Connection对象
    conn.close()

if __name__ == '__main__':
    main()

猜你喜欢

转载自blog.csdn.net/weixin_44079370/article/details/109813187