一、安装&启动
1、安装
https://downloads.mysql.com/archives/community/,进入网址后选择合适的版本,具体设置过程并不会(找人帮忙装的)
2、测试
安装好之后打开终端,输入which mysql,回车检察mysql安装路径/usr/local/mysql/bin/mysql,然后输入/usr/local/mysql/bin,进入到mysql中,输入mysql -u root -p,弹出输入暗码的提示,然后输入mysql暗码,这就已经启动了mysql。
如果需要启动mysql,只需要打开终端输入mysql -u root -p,如果不利用mysql了就可以输入exit退出体系。
3、设置和修改root暗码
window体系中默认的root账号没有暗码,如果想为账户设定暗码,可以在登岸之后实验下令:set password = password(“root123”),但这个前提是可以大概进得去数据库,要么数据库本来就没暗码要么就是知道原来暗码但是要设定新的暗码。
忘记暗码时:
(1)修改设置文件,在【mysql】节点下添加skip-grant-tables = 1;
(2)重启mysql,再次登岸时,不需要暗码直接可以进去了,重启指令:[win] net stop mysql、net start mysql,[Mac] study mysql.server restart;
(3)重庆之后无需暗码就可登岸 mysql -u -root -p;
(4)进入数据库后实验修改暗码下令: use mysql;点击回车后实验update user set authentication_string = password(‘新暗码’), password_last_changed = now() where user = ‘root’。
(5)退出并再次修改设置文件,删除[mysql]节点下的skip-grant-tables =1
(6)再次重启,以后就可以利用暗码登岸了。
注:sql语句中–代表注释。
二、数据库管理
安装之后,可以通过指令让Mysql作出一些文件操作。
1、内置客户端操作
(1)检察当前所有的数据库(show databases);
(2)创建数据库:create database learn(数据库名);
但是当我们在界说一个数据库的时间往往会同时界说好它的编码规则,因此下令可以写作:create database learning
(数据库名)DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
(3)删除数据库:drop database learning(数据库名);
(4)进入数据库/利用数据库:use database test_shcema(数据库名);
(5)检察数据库下包罗的表:show tables;
(6)退出:exit
退出指令exit并不需要封号,如果需要退出本下令行,只需要输入\c即可。
2、用python操作mysql的代码
用python来操控mysql时,代码跟内置代码有些许不同,python下令如下:
(1)连接Mysql
- import pymysql
- #连接mysql(用到了网络编程socket)
- conn = pymysql.connect(
- host='127.0.0.1',
- #port = 3306,
- user='root',
- password='12345678',
- database='test_schema',
- charset='utf8'
- )
- #构造游标,通过游标来操控mysql
- cursor = conn.cursor()
复制代码 (2)参看数据库
- #通过游标发送命令
- cursor.execute('show databases')
- #通过游标来获取mysql的返回值
- result = cursor.fetchall()
- print(result)
- #(('information_schema',), ('mysql',), ('performance_schema',), ('sys',), ('test_schema',))
复制代码 (3)创建数据库
需要注意的是,如果是查询的话,利用cursor.fetchall()即可,如果是需要增编削就需要用到conn.commit()
- cursor.execute("create database learing default charset utf8 collate utf8_general_ci")
- #增删改查都需要用conn.commit()指令
- conn.commit()
- #通过游标发送命令
- cursor.execute('show databases')
- #通过游标来获取mysql的返回值
- result = cursor.fetchall()
- print(result)
- #(('information_schema',), ('learing',), ('mysql',), ('performance_schema',), ('sys',), ('test_schema',))
复制代码 (4)删除数据库
- cursor.execute("drop database learing")
- conn.commit()
- cursor.execute('show databases')
- result1 = cursor.fetchall()
- print(result1)
- #(('information_schema',), ('mysql',), ('performance_schema',), ('sys',), ('test_schema',))
复制代码 (5)查询数据库中的表
- cursor.execute('use test_schema')
- cursor.execute('show tables')
- result2 = cursor.fetchall()
- print(result2)
- #()
复制代码 三、表管理
1、内置客户端操作
在本文中不再先容常见的数据范例(整数、字符串),因为之前的博客中有具体记录。
(1)use 数据库 + show tables
在对表table进行操作之前,必须先打开数据库use+数据库名。
(2)创建表格
create table 表名(
列名 范例,
列名 范例,
列名 范例
)default charset=utf8;
- mysql> create table tb1(
- -> id int,
- -> name varchar(16)
- -> ) default charset=utf8;
复制代码
1)设置字段是否能为空值
比如name 设置为“不能为空值“,email设置为“可以为空值“。
- mysql> create table tb2(
- -> id int,
- -> name varchar(16) not null,
- -> email varchar(32) null,
- -> age int
- -> )default charset=utf8;
复制代码
2)设置字段的默认值
- mysql> create table tb3(
- -> id int,
- -> name varchar(16) not null,
- -> email varchar(32) not null,
- -> age int default 3
- -> )default charset=utf8;
复制代码
3)设置字段为主键
- mysql> create table tb4(
- -> id int primary key,
- -> name varchar(16) not null,
- -> email varchar(32) null,
- -> age int default 3
- -> )default charset=utf8;
复制代码 4)设置字段为自增长
主键一般用于表现当前这条数据的ID编号(雷同于人的身份证),需要我们自己维护一个不重复的值,而这又是比较繁琐的操作,以是在数据库中一般会将主键和自增相结合。
- mysql> create table tb5(
- -> id int not null auto_increment primary key,
- -> name varchar(16) not null,
- -> email varchar(32) null,
- -> age int default 3
- -> )default charset=utf8;
复制代码
注:一个表只能由一个自增长列,一般是主键
5)删除表
drop table 表名
6)清空表
delete from 表名
truncate 表名(速率快,但是无法撤销)
(3)修改表
1)添加列
- alter table 表名 add 列名 类型;
- alter table 表名 add 列名 类型 default 默认值;
- alter table 表名 add 列名 类型 not null default 默认值;
- alter table 表名 add 列名 类型 not null primary key auto_increment;
复制代码 我们检察表字段的属性,然后进行修改
增长一个pwd字段,设置为不能为空值
alter table tb2 add pwd varchar(64) not null;
然后再去检察表字段属性:
2)删除列
alter table 表名 drop column 列名;
- alter table tb2 drop column pwd;
复制代码 3)修改列属性和名称
alter table 表名 change 原列名 新列名 新范例;
- alter table tb2 change id id1 int not null primary key auto_increment;
复制代码 4)修改列 设置默认值
alter table 表名 alter 列名 set default 默认值;
- alter table tb2 alter age set default 20;
复制代码 5)删除列的默认值
alter table 表名 alter 列名 drop default;
- alter table tb2 alter age drop default;
复制代码 6)添加主键
alter table 表名 add primary key(id);
- Alter table tb3 add primary key(id);
复制代码
7)删除主键
alter table 表名 drop primary key;
- Alter table tb3 drop primary key;
复制代码
(4)数据范例:文本
1)text
text用于保存变长的大字符串,最多储存65535个字符,一般环境下长文本会用text范例,比方:消息和文章。
- mysql> create table L1(
- -> id int not null auto_increment primary key,
- -> title varchar(128),
- -> context text
- -> )default charset=utf8;
复制代码 2)mediumtext
中文本,可以保存16777215个字符串。
3)longtext
长文本,最多可以保存4294967295个字符串。
(5)数据范例:时间
1)datetime
原样子输入原样输出;
2)timestap
timestap吧客户端插入的时间从当前时区转化为UTC(天下尺度时间)进行存储,查询时,将其又转化为客户端当前的时并进行返回。而datetime不做任何改变,原杨输出和输入。
- mysql> create table L2(
- -> id int not null auto_increment primary key,
- -> Dd datetime,
- -> Tt timestamp
- -> )default charset=utf8;
复制代码 插入数据
- insert into L2(dd,tt) values ("2025-11-11 10:45:40", "2025-11-11 10:45:40");
复制代码
可以看出:datetime和timestamp格式下,输出的时间是一样单,但是当我们改了时区后Tt体现的时间将会有变革。
- mysql> show variables like '%time_zone%';
- +------------------+--------+
- | Variable_name | Value |
- +------------------+--------+
- | system_time_zone | CST |
- | time_zone | SYSTEM |
- +------------------+--------+
- 2 rows in set (0.02 sec)
复制代码 当我们改变体系时区后再次去看时间数据的时间就会发现,timestap和datetime返回的数值不同了。
- mysql> set time_zone='+0:00';
- Query OK, 0 rows affected (0.00 sec)
- mysql> show variables like '%time_zone%';
- +------------------+--------+
- | Variable_name | Value |
- +------------------+--------+
- | system_time_zone | CST |
- | time_zone | +00:00 |
- +------------------+--------+
- 2 rows in set (0.00 sec)
- mysql> select * from L2;
- +----+---------------------+---------------------+
- | id | Dd | Tt |
- +----+---------------------+---------------------+
- | 1 | 2025-11-11 10:45:40 | 2025-11-11 02:45:40 |
- +----+---------------------+---------------------+
- 1 row in set (0.00 sec)
复制代码 2、python代码操作
- conn = pymysql.connect(
- host='localhost',
- #port = 3306,
- user='root',
- password='12345678',
- database='test_schema',
- charset='utf8'
- )
- #构造游标,通过游标来操控mysql
- cursor = conn.cursor()
- #进入数据库创建表
- cursor.execute('use test_schema')
- sql = """
- create table L_(
- id int not null primary key auto_increment,
- title varchar(128),
- content text,
- ctime datetime
- )default charset=utf8;
- """
- cursor.execute(sql)
- conn.commit()
- cursor.execute('show tables')
- result2 = cursor.fetchall()
- print(result2)
- #(('L1',), ('L2',), ('L_',), ('tb1',), ('tb2',), ('tb3',), ('tb4',), ('tb5',))
复制代码 四、数据行
当数据库和数据表创建完成之后,就需要对数据表中的内容进行增编削查了。
1、内置客户端操作
数据行操作的相关指令如下:
(1)新增数据
insert into 表名(列名,列名,列名) values(值,值,值)
- insert into tb5(name, age) values('高宇星','18')
- insert into tb5(name, age) values('朱朱','20'),('alex', '26')
- insert into tb5 values('7','豪哼','22'),('8','你好', '27') --省掉列名之后,将数据对应输入
复制代码 (2)删除数据
delete from 表名
delete from 表名 where 条件
- delete from tb5
- delete from tb5 where age='30'
复制代码 (3)修改数据
update 表名 set 列名=值;
update 表名 set 列名=值 where 条件;
- update tb5 set name='美女'; --将姓名这一列全部都改成美女
- update tb5 set name='宇宙超级无敌大美女' where id=1;
- update tb5 set age=age+1 where id=3;
- update tb5 set name=concat(name,'123') where id=4; --concat一个函数,可以拼接字符
复制代码 (4)查询数据
select * from 表名;
select 列名,列名,列名 from 表名;
select 列名,列名 as 别名,别名 from 表名;
select * from 表名 where 条件;
- select * from tb5;
- select id,name,age from tb5;
- select id,name as N,age from tb5; --name列字段会变为N
- select id,name as N,age,111 from tb5; --字段111本来时没有的,但是在查询的时候会多出一个字段,名字为111,数据为空
复制代码 2、python代码操作
python实验下令增编削查
- import pymysql
- #连接Mysql,自动执行use test_schema--进入指定数据库
- conn = pymysql.connect(
- host='localhost',
- user='root',
- password='12345678',
- database='test_schema',
- charset='utf8'
- )
- cursor = conn.cursor()
- #1、新增
- cursor.execute("insert into tb5(name, age) values('高宇星', 18)")
- conn.commit()
- cursor.execute('select * from tb5')
- print(cursor.fetchall())
- #2、删除
- cursor.execute('delete from tb5 where id=9')
- conn.commit()
- #3、修改
- cursor.execute('update tb5 set name="xx" where id=10')
- conn.commit()
- #4、查询
- cursor.execute('select * from tb5')
- data = cursor.fetchall()
- print(data)
- # ((10, 'xx', 18), (11, '高宇星', 18))
- #关闭连接
- conn.close()
复制代码 案例:实现一个用户管理体系
先利用Mysql自带的客户端创建相关数据库和表结构(相当于先创建好Excel结构),然后再在程序中实验编写相应的功能,实现 注册、登录等功能。
在终端利用mysql语言创建了表格users
- mysql> use test_schema;
- Reading table information for completion of table and column names
- You can turn off this feature to get a quicker startup with -A
- Database changed
- mysql> create table users(
- -> id int not null primary key auto_increment,
- -> name varchar(32),
- -> password varchar(64)
- -> )default charset=utf8;
- Query OK, 0 rows affected, 1 warning (0.03 sec)
复制代码 在pycharm中编写实验代码
- import pymysql
- def register():
- print("用户注册")
- user = input("请输入用户名:")
- password = input("请输入密码:")
- #连接指定数据
- conn = pymysql.connect(
- host='localhost',
- user='root',
- password='12345678',
- database='test_schema',
- charset='utf8'
- )
- cursor = conn.cursor()
- #执行SQL语句(有sql注入风险)
- sql = 'insert into users(name, password) values("{}","{}")'.format(user, password)
- cursor.execute(sql)
- conn.connect()
- #关闭数据库
- cursor.close()
- conn.close()
- print("注册成功,用户名:{}, 密码:{}".format(user, password))
- def login():
- print("用户登录")
- user = input("请输入用户名:")
- password = input("请输入密码:")
- # 连接指定数据
- conn = pymysql.connect(
- host='localhost',
- user='root',
- password='12345678',
- database='test_schema',
- charset='utf8'
- )
- cursor = conn.cursor()
- #执行sql语句(有sql注入风险)
- sql = "select * from users where name='{}' and password='{}'".format(user, password)
- cursor.execute(sql)
- result = cursor.fetchone() #去获取一条数据
- if result:
- print("登录成功", result)
- else:
- print("登录失败")
- def run():
- choice = input("1.注册;2.登录,请输入:")
- if choice == '1':
- register()
- elif choice == '2':
- login()
- else:
- print("输入错误")
- if __name__ == '__main__':
- run()
复制代码 在实验程序的时间,选择1选项进行注册,然后在输入三条数据后检察users表

由此可以看到三个账户的信息。
接着我们选择登录选项,在输入信息后从数据表中查询,看看是否是正确的信息,如果fetchone返回数据的话就是正确的,可以正常登录的,返回数据None的话,就阐明数据不正确,无法成功登录。


五、关于SQL注入
如果客户在输入sql语句时,把name赋值为’or 1=1–即使输入错误的暗码也会通过验证,这就是SQL注入标题。
因为拼接起来的SQL语句为:
- select * from users where name = ''or 1=1 --' and password='123''
复制代码 如许查询语句的含义就变成了查询name为空值或者 1=1 的数据 ‘–’在sql语句中是注释的意思背面的and就没有任何作用了,以是fetchone可以返回数据,并且通过验证登录成功。
那么如何在python中避免sql注入的标题呢?
牢记不要利用python的字符串格式化,而是要用pymysql中的execute方法,并把formate方法改为占位符方法。
- def login():
- print("用户登录")
- user = input("请输入用户名:")
- password = input("请输入密码:")
- # 连接指定数据
- conn = pymysql.connect(
- host='localhost',
- user='root',
- password='12345678',
- database='test_schema',
- charset='utf8'
- )
- cursor = conn.cursor()
- #执行sql语句(有sql注入风险)
- #sql = "select * from users where name='{}' and password='{}'".format(user, password)
- #cursor.execute(sql)
- cursor.execute("select * from users where name=%(name)s and password=%(pwd)s", {'name':user, 'pwd':password})
- result = cursor.fetchone() #去获取一条数据
- if result:
- print("登录成功", result)
- else:
- print("登录失败")
复制代码 因为利用sql语句可以自动格式化并检查是否有非法的其他字符,而且代码内部会做转译。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |