【python开辟】安装&设置&启动+数据库管理+表管理+数据行管理+python操作My ...

打印 上一主题 下一主题

主题 912|帖子 912|积分 2736

一、安装&启动

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

  1. import pymysql
  2. #连接mysql(用到了网络编程socket)
  3. conn = pymysql.connect(
  4.     host='127.0.0.1',
  5.     #port = 3306,
  6.     user='root',
  7.     password='12345678',
  8.     database='test_schema',
  9.     charset='utf8'
  10. )
  11. #构造游标,通过游标来操控mysql
  12. cursor = conn.cursor()
复制代码
(2)参看数据库

  1. #通过游标发送命令
  2. cursor.execute('show databases')
  3. #通过游标来获取mysql的返回值
  4. result = cursor.fetchall()
  5. print(result)
  6. #(('information_schema',), ('mysql',), ('performance_schema',), ('sys',), ('test_schema',))
复制代码
(3)创建数据库

需要注意的是,如果是查询的话,利用cursor.fetchall()即可,如果是需要增编削就需要用到conn.commit()
  1. cursor.execute("create database learing default charset utf8 collate utf8_general_ci")
  2. #增删改查都需要用conn.commit()指令
  3. conn.commit()
  4. #通过游标发送命令
  5. cursor.execute('show databases')
  6. #通过游标来获取mysql的返回值
  7. result = cursor.fetchall()
  8. print(result)
  9. #(('information_schema',), ('learing',), ('mysql',), ('performance_schema',), ('sys',), ('test_schema',))
复制代码
(4)删除数据库

  1. cursor.execute("drop database learing")
  2. conn.commit()
  3. cursor.execute('show databases')
  4. result1 = cursor.fetchall()
  5. print(result1)
  6. #(('information_schema',), ('mysql',), ('performance_schema',), ('sys',), ('test_schema',))
复制代码
(5)查询数据库中的表

  1. cursor.execute('use test_schema')
  2. cursor.execute('show tables')
  3. result2 = cursor.fetchall()
  4. print(result2)
  5. #()
复制代码
三、表管理

1、内置客户端操作

在本文中不再先容常见的数据范例(整数、字符串),因为之前的博客中有具体记录。
(1)use 数据库 + show tables

在对表table进行操作之前,必须先打开数据库use+数据库名。

(2)创建表格

create table 表名(
列名 范例,
列名 范例,
列名 范例
)default charset=utf8;
  1. mysql> create table tb1(
  2.     -> id int,
  3.     -> name varchar(16)
  4.     -> ) default charset=utf8;
复制代码

1)设置字段是否能为空值

比如name 设置为“不能为空值“,email设置为“可以为空值“。
  1. mysql> create table tb2(
  2.     -> id int,
  3.     -> name varchar(16) not null,
  4.     -> email varchar(32) null,
  5.     -> age int
  6.     -> )default charset=utf8;
复制代码

2)设置字段的默认值

  1. mysql> create table tb3(
  2.     -> id int,
  3.     -> name varchar(16) not null,
  4.     -> email varchar(32) not null,
  5.     -> age int default 3
  6.     -> )default charset=utf8;
复制代码

3)设置字段为主键

  1. mysql> create table tb4(
  2.     -> id  int primary key,
  3.     -> name varchar(16) not null,
  4.     -> email varchar(32) null,
  5.     -> age int default 3
  6.     -> )default charset=utf8;
复制代码
4)设置字段为自增长

主键一般用于表现当前这条数据的ID编号(雷同于人的身份证),需要我们自己维护一个不重复的值,而这又是比较繁琐的操作,以是在数据库中一般会将主键和自增相结合。
  1. mysql> create table tb5(
  2.     -> id int not null auto_increment primary key,
  3.     -> name varchar(16) not null,
  4.     -> email varchar(32) null,
  5.     -> age int default 3
  6.     -> )default charset=utf8;
复制代码

注:一个表只能由一个自增长列,一般是主键
5)删除表

drop table 表名
6)清空表

delete from 表名
truncate 表名(速率快,但是无法撤销)
(3)修改表

1)添加列

  1. alter table 表名 add 列名 类型;
  2. alter table 表名 add 列名 类型 default 默认值;
  3. alter table 表名 add 列名 类型 not null default 默认值;
  4. alter table 表名 add 列名 类型 not null primary key auto_increment;
复制代码
我们检察表字段的属性,然后进行修改

增长一个pwd字段,设置为不能为空值
alter table tb2 add pwd varchar(64) not null;
然后再去检察表字段属性:

2)删除列

alter table 表名 drop column 列名;
  1. alter table tb2 drop column pwd;
复制代码
3)修改列属性和名称

alter table 表名 change 原列名 新列名 新范例;
  1. alter table tb2 change id id1 int not null primary key auto_increment;
复制代码
4)修改列 设置默认值

alter table 表名 alter 列名 set default 默认值;
  1. alter table tb2 alter age set default 20;
复制代码
5)删除列的默认值

alter table 表名 alter 列名 drop default;
  1. alter table tb2 alter age drop default;
复制代码
6)添加主键

alter table 表名 add primary key(id);
  1. Alter table tb3 add primary key(id);
复制代码

7)删除主键

alter table 表名 drop primary key;
  1. Alter table tb3 drop primary key;
复制代码

(4)数据范例:文本

1)text

text用于保存变长的大字符串,最多储存65535个字符,一般环境下长文本会用text范例,比方:消息和文章。
  1. mysql> create table L1(
  2.     -> id int not null auto_increment primary key,
  3.     -> title varchar(128),
  4.     -> context text
  5.     -> )default charset=utf8;
复制代码
2)mediumtext

中文本,可以保存16777215个字符串。
3)longtext

长文本,最多可以保存4294967295个字符串。
(5)数据范例:时间

1)datetime

原样子输入原样输出;
2)timestap

timestap吧客户端插入的时间从当前时区转化为UTC(天下尺度时间)进行存储,查询时,将其又转化为客户端当前的时并进行返回。而datetime不做任何改变,原杨输出和输入。
  1. mysql> create table L2(
  2.     -> id int not null auto_increment primary key,
  3.     -> Dd datetime,
  4.     -> Tt timestamp
  5.     -> )default charset=utf8;
复制代码
插入数据
  1. insert into L2(dd,tt) values ("2025-11-11 10:45:40", "2025-11-11 10:45:40");
复制代码

可以看出:datetime和timestamp格式下,输出的时间是一样单,但是当我们改了时区后Tt体现的时间将会有变革。
  1. mysql> show variables like '%time_zone%';
  2. +------------------+--------+
  3. | Variable_name    | Value  |
  4. +------------------+--------+
  5. | system_time_zone | CST    |
  6. | time_zone        | SYSTEM |
  7. +------------------+--------+
  8. 2 rows in set (0.02 sec)
复制代码
当我们改变体系时区后再次去看时间数据的时间就会发现,timestap和datetime返回的数值不同了。
  1. mysql> set time_zone='+0:00';
  2. Query OK, 0 rows affected (0.00 sec)
  3. mysql> show variables like '%time_zone%';
  4. +------------------+--------+
  5. | Variable_name    | Value  |
  6. +------------------+--------+
  7. | system_time_zone | CST    |
  8. | time_zone        | +00:00 |
  9. +------------------+--------+
  10. 2 rows in set (0.00 sec)
  11. mysql> select * from L2;
  12. +----+---------------------+---------------------+
  13. | id | Dd                  | Tt                  |
  14. +----+---------------------+---------------------+
  15. |  1 | 2025-11-11 10:45:40 | 2025-11-11 02:45:40 |
  16. +----+---------------------+---------------------+
  17. 1 row in set (0.00 sec)
复制代码
2、python代码操作

  1. conn = pymysql.connect(
  2.     host='localhost',
  3.     #port = 3306,
  4.     user='root',
  5.     password='12345678',
  6.     database='test_schema',
  7.     charset='utf8'
  8. )
  9. #构造游标,通过游标来操控mysql
  10. cursor = conn.cursor()
  11. #进入数据库创建表
  12. cursor.execute('use test_schema')
  13. sql = """
  14. create table L_(
  15. id int not null primary key auto_increment,
  16. title varchar(128),
  17. content text,
  18. ctime datetime
  19. )default charset=utf8;
  20. """
  21. cursor.execute(sql)
  22. conn.commit()
  23. cursor.execute('show tables')
  24. result2 = cursor.fetchall()
  25. print(result2)
  26. #(('L1',), ('L2',), ('L_',), ('tb1',), ('tb2',), ('tb3',), ('tb4',), ('tb5',))
复制代码
四、数据行

当数据库和数据表创建完成之后,就需要对数据表中的内容进行增编削查了。
1、内置客户端操作

数据行操作的相关指令如下:
(1)新增数据

insert into 表名(列名,列名,列名) values(值,值,值)
  1. insert into tb5(name, age) values('高宇星','18')
  2. insert into tb5(name, age) values('朱朱','20'),('alex', '26')
  3. insert into tb5 values('7','豪哼','22'),('8','你好', '27') --省掉列名之后,将数据对应输入
复制代码
(2)删除数据

delete from 表名
delete from 表名 where 条件
  1. delete from tb5
  2. delete from tb5 where age='30'
复制代码
(3)修改数据

update 表名 set 列名=值;
update 表名 set 列名=值 where 条件;
  1. update tb5 set name='美女'; --将姓名这一列全部都改成美女
  2. update tb5 set name='宇宙超级无敌大美女' where id=1;
  3. update tb5 set age=age+1 where id=3;
  4. update tb5 set name=concat(name,'123') where id=4; --concat一个函数,可以拼接字符
复制代码
(4)查询数据

select * from 表名;
select 列名,列名,列名 from 表名;
select 列名,列名 as 别名,别名 from 表名;
select * from 表名 where 条件;
  1. select * from tb5;
  2. select id,name,age from tb5;
  3. select id,name as N,age from tb5;    --name列字段会变为N
  4. select id,name as N,age,111 from tb5;  --字段111本来时没有的,但是在查询的时候会多出一个字段,名字为111,数据为空
复制代码
2、python代码操作

python实验下令增编削查

  1. import pymysql
  2. #连接Mysql,自动执行use test_schema--进入指定数据库
  3. conn = pymysql.connect(
  4.     host='localhost',
  5.     user='root',
  6.     password='12345678',
  7.     database='test_schema',
  8.     charset='utf8'
  9. )
  10. cursor = conn.cursor()
  11. #1、新增
  12. cursor.execute("insert into tb5(name, age) values('高宇星', 18)")
  13. conn.commit()
  14. cursor.execute('select * from tb5')
  15. print(cursor.fetchall())
  16. #2、删除
  17. cursor.execute('delete from tb5 where id=9')
  18. conn.commit()
  19. #3、修改
  20. cursor.execute('update tb5 set name="xx" where id=10')
  21. conn.commit()
  22. #4、查询
  23. cursor.execute('select * from tb5')
  24. data = cursor.fetchall()
  25. print(data)
  26. # ((10, 'xx', 18), (11, '高宇星', 18))
  27. #关闭连接
  28. conn.close()
复制代码
案例:实现一个用户管理体系

先利用Mysql自带的客户端创建相关数据库和表结构(相当于先创建好Excel结构),然后再在程序中实验编写相应的功能,实现 注册、登录等功能。
在终端利用mysql语言创建了表格users
  1. mysql> use test_schema;
  2. Reading table information for completion of table and column names
  3. You can turn off this feature to get a quicker startup with -A
  4. Database changed
  5. mysql> create table users(
  6.     -> id int not null primary key auto_increment,
  7.     -> name varchar(32),
  8.     -> password varchar(64)
  9.     -> )default charset=utf8;
  10. Query OK, 0 rows affected, 1 warning (0.03 sec)
复制代码
在pycharm中编写实验代码
  1. import pymysql
  2. def register():
  3.     print("用户注册")
  4.     user = input("请输入用户名:")
  5.     password = input("请输入密码:")
  6.     #连接指定数据
  7.     conn = pymysql.connect(
  8.         host='localhost',
  9.         user='root',
  10.         password='12345678',
  11.         database='test_schema',
  12.         charset='utf8'
  13.     )
  14.     cursor = conn.cursor()
  15.     #执行SQL语句(有sql注入风险)
  16.     sql = 'insert into users(name, password) values("{}","{}")'.format(user, password)
  17.     cursor.execute(sql)
  18.     conn.connect()
  19.     #关闭数据库
  20.     cursor.close()
  21.     conn.close()
  22.     print("注册成功,用户名:{}, 密码:{}".format(user, password))
  23. def login():
  24.     print("用户登录")
  25.     user = input("请输入用户名:")
  26.     password = input("请输入密码:")
  27.     # 连接指定数据
  28.     conn = pymysql.connect(
  29.         host='localhost',
  30.         user='root',
  31.         password='12345678',
  32.         database='test_schema',
  33.         charset='utf8'
  34.     )
  35.     cursor = conn.cursor()
  36.     #执行sql语句(有sql注入风险)
  37.     sql = "select * from users where name='{}' and password='{}'".format(user, password)
  38.     cursor.execute(sql)
  39.     result = cursor.fetchone() #去获取一条数据
  40.     if result:
  41.         print("登录成功", result)
  42.     else:
  43.         print("登录失败")
  44. def run():
  45.     choice = input("1.注册;2.登录,请输入:")
  46.     if choice == '1':
  47.         register()
  48.     elif choice == '2':
  49.         login()
  50.     else:
  51.         print("输入错误")
  52. if __name__ == '__main__':
  53.     run()
复制代码
在实验程序的时间,选择1选项进行注册,然后在输入三条数据后检察users表

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


五、关于SQL注入

如果客户在输入sql语句时,把name赋值为’or 1=1–即使输入错误的暗码也会通过验证,这就是SQL注入标题。
因为拼接起来的SQL语句为:
  1. select * from users where name = ''or 1=1 --' and password='123''
复制代码
如许查询语句的含义就变成了查询name为空值或者 1=1 的数据 ‘–’在sql语句中是注释的意思背面的and就没有任何作用了,以是fetchone可以返回数据,并且通过验证登录成功。
那么如何在python中避免sql注入的标题呢?
牢记不要利用python的字符串格式化,而是要用pymysql中的execute方法,并把formate方法改为占位符方法。
  1. def login():
  2.     print("用户登录")
  3.     user = input("请输入用户名:")
  4.     password = input("请输入密码:")
  5.     # 连接指定数据
  6.     conn = pymysql.connect(
  7.         host='localhost',
  8.         user='root',
  9.         password='12345678',
  10.         database='test_schema',
  11.         charset='utf8'
  12.     )
  13.     cursor = conn.cursor()
  14.     #执行sql语句(有sql注入风险)
  15.     #sql = "select * from users where name='{}' and password='{}'".format(user, password)
  16.     #cursor.execute(sql)
  17.     cursor.execute("select * from users where name=%(name)s and password=%(pwd)s", {'name':user, 'pwd':password})
  18.     result = cursor.fetchone() #去获取一条数据
  19.     if result:
  20.         print("登录成功", result)
  21.     else:
  22.         print("登录失败")
复制代码
因为利用sql语句可以自动格式化并检查是否有非法的其他字符,而且代码内部会做转译。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

嚴華

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表