Getting started with mysql (combined with python)

getting started with mysql

  • mysql introduction: MySQL , originally a sun company, was later acquired by Oracle. Almost all Internet companies are now using it. [Free + Charged]

Install, configure, start

Version

  • Version 5.x is now the mainstream version in Internet companies, including Toutiao, Meitu, Baidu, Tencent and other mainstream versions of Internet companies.
  • In version 8.x, some new functions such as window functions, persistent configuration, and hidden indexes have been added.

Install

Step 1: Download and install

https://downloads.mysql.com/archives/community/

windows(X86,64-bit).zipArchive

Step 2: Unzip to any folder

It is recommended to decompress to the software installation directory, for example:

Step 3: Create Configuration File

The file created in the MySQL installation directory my.iniis used as the MySQL configuration file.
insert image description here

In fact, MySQL configuration files can be placed in many directories. The following figure shows the priority of configuration files:

It is strongly recommended that you put the configuration files in the MySQL installation directory, so that when you want to install multiple versions of MySQL on your computer in the future, the configuration files can be independent of each other without affecting each other.

Note: If there are MySQL configuration files in the above-mentioned other directories of your computer, it is recommended to delete them, otherwise it may affect the startup of MySQL.

Step 4: Initialize

  • initialize-insecure
>>> "C:\Program Files\mysql-5.7.31-winx64\bin\mysqld.exe"  --initialize-insecure

When the initialization command is executed, it will automatically read the configuration file and perform initialization. This process will mainly do two things:

  • The data directory is automatically created, and our data will be stored in this directory in the future.

  • At the same time, create some necessary data, such as the default account root (no password), which is used to log in to MySQL and operate MySQL through instructions.

If there is an error (msvcr120.dll does not exist) during the installation of windows, please download and install the following two patches:

  • vcredist:https://www.microsoft.com/zh-cn/download/confirmation.aspx?id=40784 (主要)

  • dirctx:https://www.microsoft.com/zh-CN/download/details.aspx?id=35

Step 5: Start

There are two common ways to start MySQL:

  • Temporary activation
>>> "C:\Program Files\mysql-5.7.31-winx64\bin\mysqld.exe"

Note: The program will hang at this time, and it can receive MySQL commands from the client internally, and it can stop running by closing the window or pressing Ctrl+c.

This startup method is cumbersome to manually execute the command every time it is turned on or wants to be turned on.

  • Make windows service, based on windows service management.
>>>"C:\Program Files\mysql-5.7.31-winx64\bin\mysqld.exe" --install mysql57
  • After creating the service, you can start and stop the service with commands, for example:
>>> net start mysql57
>>> net stop mysql57

You can also click the button to start and close the service in the service management of the window. For example:

insert image description here

If you no longer want to use the window service in the future, you can also delete the created MySQL service.

  • remove mysql57
>>>"C:\Program Files\mysql-5.7.31-winx64\bin\mysqld.exe" --remove mysql57

Step 6: Test connection to MySQL

After installing and starting MySQL, you can connect to MySQL to test whether it has been installed correctly and started successfully.

When installing MySQL, a tool (client) is also automatically installed, allowing us to quickly connect to MySQL and send commands.

insert image description here

Note: If you add the bin directory to the environment variable, you don't need to re-enter the absolute path every time you run the command.
insert image description here

If the above process is completed, it proves that your installation and startup process is completed.

configuration

About configuration files

In the above process, we only added a few configurations in the configuration file.

In fact, there are many configuration items, and which configuration items have default values. If we do not configure, MySQL will automatically use the default values.

about password

1. Set and change the root password

In the windows system, the default root account of the module has no password. If you want to set a password for the account, you can execute after successfully logging in with the root account:

  • set password = password(“root”)

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-YANE5UCQ-1630337169420)(assets/image-20210830230416853-16303358578267.png)]

2. Forgot root password

If you forgot the password of the MySQL account.

  • Modify the configuration file and add it under the [mysqld] nodeskip-grant-tables=1
[mysqld]
...
skip-grant-tables=1
...
  • Restart MySQL, and when you log in again, you can enter directly without a password

    • windows restart
    net stop mysql57
    net start mysql57
    
  • After a reboot, the unordered password is accessible.

>>> mysql -u root -p
  • After entering the database, execute the command to change the password
use mysql;
update user set authentication_string = password('新密码'),password_last_changed=now() where user='root';
  • Exit and modify the configuration file again, delete `skip-grant-tables=1 under the [mysqld] node
[mysqld]
...
# skip-grant-tables=1
...
  • Reboot again and you will be able to log in with the new password in the future.

2. Database Management

After installing the database, you need to start learning instructions, and let MySQL do some file operations through instructions.

If the database management system is compared with the previous file management:

database management system file management
database folder
data sheet excel files in the folder

2.1 Built-in client operation

After connecting to MySQL, execute the following commands (generally called SQL statements) to operate on MySQL data.

  • View all current databases:show databases;

  • Create a database:create database 数据库名 DEFAULT CHARSET utf8 COLLATE utf8_general_ci;

create database day25db;

create database day25db DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
  • delete database: drop database 数据库名;

  • Into data (into file):use 数据库;

Example:

# 1.登录MySQL
wupeiqi@wupeiqideMBP ~ % /usr/local/mysql/bin/mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 5
Server version: 5.7.31 MySQL Community Server (GPL)

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

# 2.查看当前数据库
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

# 3. 创建数据库:  create database 数据库名 default charset 编码 collate 排序规则;
mysql> create database db1 default charset utf8 collate utf8_general_ci;
Query OK, 1 row affected (0.00 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| db1                |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.01 sec)

# 4. 删除数据库
mysql> drop database db1;
Query OK, 0 rows affected (0.00 sec)

# 5. 查看当前数据库
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

# 6. 进入数据库
mysql> use mysql;
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
# 7. 进入mysql数据库(文件夹),查看此数据库下的所有表。
mysql> show tables;
+---------------------------+
| Tables_in_mysql           |
+---------------------------+
| columns_priv              |
| db                        |
| engine_cost               |
| event                     |
| func                      |
| general_log               |
| gtid_executed             |
| help_category             |
| help_keyword              |
| help_relation             |
| help_topic                |
| innodb_index_stats        |
| innodb_table_stats        |
| ndb_binlog_index          |
| plugin                    |
| proc                      |
| procs_priv                |
| proxies_priv              |
| server_cost               |
| servers                   |
| slave_master_info         |
| slave_relay_log_info      |
| slave_worker_info         |
| slow_log                  |
| tables_priv               |
| time_zone                 |
| time_zone_leap_second     |
| time_zone_name            |
| time_zone_transition      |
| time_zone_transition_type |
| user                      |
+---------------------------+
31 rows in set (0.00 sec)

# 8. 退出
mysql>exit;

2.2 Python code operation

No matter what method is used to connect to MySQL, the instructions sent are essentially the same, but the connection method and operation form are different.

After connecting to MySQL, execute the following commands to operate on MySQL data. (same as above process)

  • View all current databasesshow databases;
  • Create a database:create database 数据库名 default charset utf8 collate utf8_general_ci;
  • delete database: drop database 数据库名;
  • Into data (into file):use 数据库;

If you want to use Python to operate MySQL, you need to install third-party modules:

pip3 install pymysql

Once installed, you can write code:

import pymysql

# 连接MySQL(socket)
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root123', charset="utf8")
cursor = conn.cursor()

# 1. 查看数据库
# 发送指令
cursor.execute("show databases")
# 获取指令的结果
result = cursor.fetchall()
print(result) # (('information_schema',), ('mysql',), ('performance_schema',), ('sys',))

# 2. 创建数据库(新增、删除、修改)
# 发送指令
cursor.execute("create database db3 default charset utf8 collate utf8_general_ci")
conn.commit()

# 3. 查看数据库
# 发送指令
cursor.execute("show databases")
# 获取指令的结果
result = cursor.fetchall()
print(result) # (('information_schema',), ('db3',), ('mysql',), ('performance_schema',), ('sys',))

# 4. 删除数据库
# 发送指令
cursor.execute("drop database db3")
conn.commit()

# 3. 查看数据库
# 发送指令
cursor.execute("show databases")
# 获取指令的结果
result = cursor.fetchall()
print(result) # (('information_schema',), ('mysql',), ('performance_schema',), ('sys',))

# 5. 进入数据库,查看表
# 发送指令
cursor.execute("use mysql")
cursor.execute("show tables")
result = cursor.fetchall()
print(result) # (('columns_priv',), ('db',), ('engine_cost',), ('event',), ('func',), ('general_log',),....

# 关闭连接
cursor.close()
conn.close()

3. Data table management

  • In fact, creating a database in a database is very similar to creating Excel, you need to specify: 表名, 列名称, 类类型(整型、字符串或其他).

3.1 Built-in client operation

Instructions for common operations on data tables:

  • Enter the database use 数据库;and view all current tables:show tables;
  • Create table structure
create table 表名(
    列名  类型,
    列名  类型,
    列名  类型
)default charset=utf8;
create table tb1(
	id int,
    name varchar(16)
)default charset=utf8;
create table tb2(
	id int,
    name varchar(16) not null,   -- 不允许为空
    email varchar(32) null,      -- 允许为空(默认)
    age int
)default charset=utf8;
create table tb3(
	id int,
    name varchar(16) not null,   -- 不允许为空
    email varchar(32) null,      -- 允许为空(默认)
    age int default 3            -- 插入数据时,如果不给age列设置值,默认值:3
)default charset=utf8;
create table tb4(
	id int primary key,			 -- 主键(不允许为空、不能重复)
    name varchar(16) not null,   -- 不允许为空
    email varchar(32) null,      -- 允许为空(默认)
    age int default 3            -- 插入数据时,如果不给age列设置值,默认值:3
)default charset=utf8;

The primary key is generally used to represent the ID number of the current piece of data (similar to a person's ID card). We need to maintain a unique value by ourselves, which is cumbersome. Therefore, in the database, the primary key and auto-increment are generally combined.

create table tb5(
	id int not null auto_increment primary key,	-- 不允许为空 & 主键 & 自增
    name varchar(16) not null,   		-- 不允许为空
    email varchar(32) null,      		-- 允许为空(默认)
    age int default 3            		-- 插入数据时,如果不给age列设置值,默认值:3
)default charset=utf8;

Note: There can only be one auto-increment column in a table [auto-increment column, generally the primary key].

  • delete tabledrop table 表名;

  • Empty the table delete from 表名;or truncate table 表名;(fast, cannot rollback undo, etc.)

  • modify table

    • add column
alter table 表名 add 列名 类型;
alter table 表名 add 列名 类型 DEFAULT 默认值;
alter table 表名 add 列名 类型 not null default 默认值;
alter table 表名 add 列名 类型 not null primary key auto_increment;
  • delete column
alter table 表名 modify column 列名 类型;
  • Modify column type + name
alter table 表名 change 原列名 新列名 新类型;
alter table  tb change id nid int not null;
alter table  tb change id id int not null default 5;
alter table  tb change id id int not null primary key auto_increment;

alter table  tb change id id int; -- 允许为空,删除默认值,删除自增。
  • Modify column defaults
ALTER TABLE 表名 ALTER 列名 SET DEFAULT 1000;
  • Remove column defaults
ALTER TABLE 表名 ALTER 列名 DROP DEFAULT;
  • add primary key
alter table 表名 add primary key(列名);
  • delete primary key
alter table 表名 drop primary key;
  • common column types
create table(
	id int,
    name varchar(16)
)default charset=utf8;
  • int[(m)][unsigned][zerofill]
int				表示有符号,取值范围:-21474836482147483647
int unsigned	表示无符号,取值范围:04294967295
int(5)zerofill	仅用于显示,当不满足5位时,按照左边补0,例如:00002;满足时,正常显示。
mysql> create table L1(id int, uid int unsigned, zid int(5) zerofill) default charset=utf8;
Query OK, 0 rows affected (0.03 sec)

mysql> insert into L1(id,uid,zid) values(1,2,3);
Query OK, 1 row affected (0.00 sec)

mysql> insert into L1(id,uid,zid) values(2147483641,4294967294,300000);
Query OK, 1 row affected (0.00 sec)

mysql> select * from L1;
+------------+------------+--------+
| id         | uid        | zid    |
+------------+------------+--------+
|          1 |          2 |  00003 |
| 2147483641 | 4294967294 | 300000 |
+------------+------------+--------+
2 rows in set (0.00 sec)

mysql> insert into L1(id,uid,zid) values(214748364100,4294967294,300000);
ERROR 1264 (22003): Out of range value for column 'id' at row 1
mysql>
  • tinyint[(m)] [unsigned] [zerofill]
有符号,取值范围:-128127.
无符号,取值范围:0255
  • bigint[(m)][unsigned][zerofill]
有符号,取值范围:-92233720368547758089223372036854775807
无符号,取值范围:018446744073709551615
  • decimal[(m[,d])] [unsigned] [zerofill]
准确的小数值,m是数字总个数(负号不算),d是小数点后个数。 m最大值为65,d最大值为30

例如:
create table L2(
	id int not null primary key auto_increment,
	salary decimal(8,2)
)default charset=utf8;
mysql> create table L2(id int not null primary key auto_increment,salary decimal(8,2))default charset=utf8;
Query OK, 0 rows affected (0.03 sec)

mysql> insert into L2(salary) values(1.28);
Query OK, 1 row affected (0.01 sec)

mysql> insert into L2(salary) values(5.289);
Query OK, 1 row affected, 1 warning (0.00 sec)

mysql> insert into L2(salary) values(5.282);
Query OK, 1 row affected, 1 warning (0.00 sec)

mysql> insert into L2(salary) values(512132.28);
Query OK, 1 row affected (0.00 sec)

mysql> insert into L2(salary) values(512132.283);
Query OK, 1 row affected, 1 warning (0.00 sec)

mysql> select * from L2;
+----+-----------+
| id | salary    |
+----+-----------+
|  1 |      1.28 |
|  2 |      5.29 |
|  3 |      5.28 |
|  4 | 512132.28 |
|  5 | 512132.28 |
+----+-----------+
5 rows in set (0.00 sec)

mysql> insert into L2(salary) values(5121321.283);
ERROR 1264 (22003): Out of range value for column 'salary' at row 1
mysql>
  • FLOAT[(M,D)] [UNSIGNED] [ZEROFILL]

    单精度浮点数,非准确小数值,m是数字总个数,d是小数点后个数。
    
  • DOUBLE[(M,D)] [UNSIGNED] [ZEROFILL]

    双精度浮点数(非准确小数值),m是数字总个数,d是小数点后个数。
    
  • char(m)

    定长字符串,m代表字符串的长度,最多可容纳255个字符。
    
    定长的体现:即使内容长度小于m,也会占用m长度。例如:char(5),数据是:yes,底层也会占用5个字符;如果超出m长度限制(默认MySQL是严格模式,所以会报错)。
        如果在配置文件中加入如下配置,
            sql-mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
        保存并重启,此时MySQL则是非严格模式,此时超过长度则自动截断(不报错)。。
    
    注意:默认底层存储是固定的长度(不够则用空格补齐),但是查询数据时,会自动将空白去除。 如果想要保留空白,在sql-mode中加入 PAD_CHAR_TO_FULL_LENGTH 即可。
    查看模式sql-mode,执行命令:show variables  like 'sql_mode';
    
    一般适用于:固定长度的内容。
    
    create table L3(
        id int not null primary key auto_increment,
        name varchar(5),
        depart char(3)
    )default charset=utf8;
    
    insert into L3(name,depart) values("alexsb","sbalex");
    
  • varchar(m)

    变长字符串,m代表字符串的长度,最多可容纳65535个字节。
    
    变长的体现:内容小于m时,会按照真实数据长度存储;如果超出m长度限制((默认MySQL是严格模式,所以会报错)。
        如果在配置文件中加入如下配置,
            sql-mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
        保存并重启,此时MySQL则是非严格模式,此时超过长度则自动截断(不报错)。
    
    例如:
    create table L3(
        id int not null primary key auto_increment,
        name varchar(5),
        depart char(3)
    )default charset=utf8;
    
    mysql> create table L3(id int not null primary key auto_increment,name varchar(5),depart char(3))default charset=utf8;
    Query OK, 0 rows affected (0.03 sec)
    
    -- 插入多行
    mysql> insert into L3(name,depart) values("wu","WU"),("wupei","ALS");
    Query OK, 2 rows affected (0.00 sec)
    Records: 2  Duplicates: 0  Warnings: 0
    
    mysql> select * from L3;
    +----+-------+--------+
    | id | name  | depart |
    +----+-------+--------+
    |  1 | wu    | WU     |
    |  2 | wupei | ALS    |
    +----+-------+--------+
    2 rows in set (0.00 sec)
    
    -- 非严格模式下,不会报错。
    mysql> insert into L3(name,depart) values("wupeiqi","ALS");
    ERROR 1406 (22001): Data too long for column 'name' at row 1
    mysql> insert into L3(name,depart) values("wupei","ALSB");
    ERROR 1406 (22001): Data too long for column 'depart' at row 1
    mysql>
    
    -- 如果 sql-mode 中加入了 PAD_CHAR_TO_FULL_LENGTH ,则查询时char时空白会保留。
    mysql> select name,length(name),depart,length(depart) from L3;
    +-------+--------------+--------+----------------+
    | name  | length(name) | depart | length(depart) |
    +-------+--------------+--------+----------------+
    | wu    |            2 | WU     |              3 |
    | wupei |            5 | ALS    |              3 |
    +-------+--------------+--------+----------------+
    4 rows in set (0.00 sec)
    mysql>
    
  • text

    text数据类型用于保存变长的大字符串,可以组多到65535 (2**161)个字符。
    
    一般情况下,长文本会用text类型。例如:文章、新闻等。
    
    create table L4(
    	id int not null primary key auto_increment,
        title varchar(128),
    	content text
    )default charset=utf8;
    
  • mediumtext

    A TEXT column with a maximum length of 16,777,215 (2**241) characters.
    
  • longtext

    A TEXT column with a maximum length of 4,294,967,295 or 4GB (2**321)
    
  • datetime

    YYYY-MM-DD HH:MM:SS(1000-01-01 00:00:00/9999-12-31 23:59:59
  • timestamp

    YYYY-MM-DD HH:MM:SS(1970-01-01 00:00:00/2037年)
    
    对于TIMESTAMP,它把客户端插入的时间从当前时区转化为UTC(世界标准时间)进行存储,查询时,将其又转化为客户端当前时区进行返回。
    
    对于DATETIME,不做任何改变,原样输入和输出。
    
    mysql> create table L5(
        -> id int not null primary key auto_increment,
        -> dt datetime,
        -> tt timestamp
        -> )default charset=utf8;
    Query OK, 0 rows affected (0.03 sec)
    
    mysql> insert into L5(dt,tt) values("2025-11-11 11:11:44", "2025-11-11 11:11:44");
    
    mysql> select * from L5;
    +----+---------------------+---------------------+
    | id | dt                  | tt                  |
    +----+---------------------+---------------------+
    |  1 | 2025-11-11 11:11:44 | 2025-11-11 11:11:44 |
    +----+---------------------+---------------------+
    1 row in set (0.00 sec)
    
    mysql> show variables like '%time_zone%';
    +------------------+--------+
    | Variable_name    | Value  |
    +------------------+--------+
    | system_time_zone | CST    | 
    | time_zone        | SYSTEM |
    +------------------+--------+
    2 rows in set (0.00 sec)
    -- “CST”指的是MySQL所在主机的系统时间,是中国标准时间的缩写,China Standard Time UT+8:00
    
    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.01 sec)
    
    mysql> select * from L5;
    +----+---------------------+---------------------+
    | id | dt                  | tt                  |
    +----+---------------------+---------------------+
    |  1 | 2025-11-11 11:11:44 | 2025-11-11 03:11:44 |
    +----+---------------------+---------------------+
    1 row in set (0.00 sec)
    
  • date

    YYYY-MM-DD(1000-01-01/9999-12-31
  • time

    HH:MM:SS('-838:59:59'/'838:59:59'

MySQL also has many other data types, such as: set, enum, TinyBlob, Blob, MediumBlob, LongBlob, etc. , see the official document for details: https://dev.mysql.com/doc/refman/5.7/en/data-types .html

3.2 MySQL code operation

After connecting to MySQL based on Python, if you want to manage the data table, the commands sent are actually the same, for example:

import pymysql

# 连接MySQL
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root123', charset="utf8")
cursor = conn.cursor()

# 1. 创建数据库
"""
cursor.execute("create database db4 default charset utf8 collate utf8_general_ci")
conn.commit()
"""

# 2. 进入数据库、查看数据表
"""
cursor.execute("use db4")
cursor.execute("show tables")
result = cursor.fetchall()
print(result)
"""

# 3. 进入数据库创建表
cursor.execute("use db4")
sql = """
create table L4(
    id int not null primary key auto_increment,
    title varchar(128),
    content text,
    ctime datetime
)default charset=utf8;
"""
cursor.execute(sql)
conn.commit()

# 4. 查看数据库中的表
"""
cursor.execute("show tables")
result = cursor.fetchall()
print(result)
"""

# 5. 其他 drop table... 略过


# 关闭连接
cursor.close()
conn.close() 

4. Data row

After the database and data table are created, it is necessary to add, delete, modify, and check the content in the data table.

4.1 Built-in client operation

The relevant SQL statements (instructions) for data row operations are as follows:

  • new data
insert into 表名 (列名,列名,列名) values(对应列的值,对应列的值,对应列的值);
insert into tb1(name,password) values('武沛齐','123123');
insert into tb1(name,password) values('武沛齐','123123'),('alex','123');

insert into tb1 values('武沛齐','123123'),('alex','123'); -- 如果表中只有2列
  • delete data
delete from 表名;
delete from 表名 where 条件;
delete from tb1;
delete from tb1 where name="wupeiqi";
delete from tb1 where name="wupeiqi" and password="123";
delete from tb1 where id>9;
  • modify data
update 表名 set 列名=;
update 表名 set 列名=where 条件;
update tb1 set name="wupeiqi";
update tb1 set name="wupeiqi" where id=1;

update tb1 set age=age+1;  -- 整型
update tb1 set age=age+1 where id=2;

update L3 set name=concat(name,"db");
update L3 set name=concat(name,"123")  where id=2;  -- concat一个函数,可以拼接字符串
  • query data
select * from 表名;
select 列名,列名,列名 from 表名;
select 列名,列名 as 别名,列名 from 表名;
select * from 表名 where 条件;
select * from tb1;
select id,name,age from tb1;
select id,name as N,age, from tb1;
select id,name as N,age, 111 from tb1;

select * from tb1 where id = 1;
select * from tb1 where id > 1;
select * from tb1 where id != 1;
select * from tb1 where name="wupeiqi" and password="123";

4.2 Python code operation

import pymysql

# 连接MySQL,自动执行 use userdb; -- 进入数据库
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root123', charset="utf8", db='userdb')
cursor = conn.cursor()


# 1.新增(需commit)
"""
cursor.execute("insert into tb1(name,password) values('武沛齐','123123')")
conn.commit()
"""

# 2.删除(需commit)
"""
cursor.execute("delete from tb1 where id=1")
conn.commit()
"""

# 3.修改(需commit)
"""
cursor.execute("update tb1 set name='xx' where id=1")
conn.commit()
"""

# 4.查询
"""
cursor.execute("select * from tb where id>10")
data = cursor.fetchone() # cursor.fetchall()
print(data)
"""

# 关闭连接
cursor.close()
conn.close()

In fact, when actually doing project development, the process is as follows:

  • The first step: Design the corresponding database & table structure according to the function of the project (it will not change frequently, it is determined at the beginning of the project design).
  • Step 2: Manipulating the data in the table structure has achieved the purpose of realizing the business logic.

For example: implement a user management system.

First use the client that comes with MySQL to create the relevant database and table structure (equivalent to creating the Excel structure first).

create database usersdb default charset utf8 collate utf8_general_ci;
create table users(
	id int not null primary key auto_increment,
    name varchar(32),
	password varchar(64)
)default charset=utf8;

Then execute and write corresponding functions in the program to realize registration, login and other functions.

import pymysql


def register():
    print("用户注册")

    user = input("请输入用户名:") # alex
    password = input("请输入密码:") # sb

    # 连接指定数据
    conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root123', charset="utf8", db="usersdb")
    cursor = conn.cursor()

    # 执行SQL语句(有SQL注入风险,稍后讲解)
    # sql = 'insert into users(name,password)values("alex","sb")'
    sql = 'insert into users(name,password) values("{}","{}")'.format(user, password)
    
    cursor.execute(sql)
    conn.commit()

    # 关闭数据库连接
    cursor.close()
    conn.close()

    print("注册成功,用户名:{},密码:{}".format(user, password))


def login():
    print("用户登录")

    user = input("请输入用户名:")
    password = input("请输入密码:")

    # 连接指定数据
    conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root123', charset="utf8", db="usersdb")
    cursor = conn.cursor()

    # 执行SQL语句(有SQL注入风险,稍后讲解)
    # sql = select * from users where name='wupeiqi' and password='123'
    sql = "select * from users where name='{}' and password='{}'".format(user, password)
    cursor.execute(sql)
    
    result = cursor.fetchone() # 去向mysql获取结果
    # None
    # (1,wupeiqi,123)
    
    
    # 关闭数据库连接
    cursor.close()
    conn.close()

    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()

5. About SQL injection

If you develop a user authentication system, the corresponding user result should be returned correctly only after the user logs in successfully.

import pymysql

# 输入用户名和密码
user = input("请输入用户名:") # ' or 1=1 -- 
pwd = input("请输入密码:") # 123


conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root123', charset="utf8",db='usersdb')
cursor = conn.cursor()

# 基于字符串格式化来 拼接SQL语句
# sql = "select * from users where name='alex' and password='123'"
# sql = "select * from users where name='' or 1=1 -- ' and password='123'"
sql = "select * from users where name='{}' and password='{}'".format(user, pwd)
cursor.execute(sql)

result = cursor.fetchone()
print(result) # None,不是None

cursor.close()
conn.close()

If the user enters: when entering user ' or 1=1 --, even if the password entered by the user does not exist, it will still pass the verification.

why?

Because during SQL splicing, the result after splicing is:

select * from users where name='' or 1=1 -- ' and password='123'

Note: means a comment in MySQL --.

So, how to avoid SQL injection in Python development?

Remember, the SQL statement should not use python's string formatting, but use the execute method of pymysql.

import pymysql

# 输入用户名和密码
user = input("请输入用户名:")
pwd = input("请输入密码:")

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root123', charset="utf8", db='userdb')

cursor = conn.cursor()

cursor.execute("select * from users where name=%s and password=%s", [user, pwd])
# 或
# cursor.execute("select * from users where name=%(n1)s and password=%(n2)s", {"n1": user, 'n2': pwd})

result = cursor.fetchone()
print(result)

cursor.close()
conn.close()

Guess you like

Origin blog.csdn.net/qq_37049812/article/details/120007848