SQL injection, use of foreign keys, ER model and relationship between tables, three paradigms

SQL injection

learning target

  • Be able to tell how to avoid SQL injection problems

1. What is SQL injection

  • SQL injection:

Simply put, sql injection is a way to leak data in the database. If some people have malicious purposes, they can use sql injection to steal data.

  • cause:

In the background, the malicious data submitted by users and SQL are spliced ​​in string form, which affects the semantics of SQL statements and eventually leads to data leakage.

To put it simply, it is to use various methods to submit data to the program and combine these data with SQL statements, so that the newly generated SQL statements have different meanings from the previous original SQL statements, so that you can use the newly generated SQL statements to obtain the desired data.

  • Prevent SQL injection

The parameterization of the SQL statement can prevent the occurrence of SQL injection. All the data parameters of the SQL statement are stored in a list and passed to the second parameter of the execute function for execution, which is the parameterization of the SQL statement.

python # Put the parameters required by the sql statement into a list my_list = [xxx,xxx,xxx] # Pass the list as the second parameter of the execute method cursor.execute(sql,my_list)

2. Non-safe SQL statements

 
 
 
 

from pymysql import connect

# Create a Connection connection
conn = connect(host='localhost', port=3306, user='root', password='mysql', database='jing_dong', charset='utf8') # Get the Cursor object cur = conn.cursor() # Get the item name that the user wants to query find_name = input("Please enter the item name:" ) # Non-safe sql statement sql = 'select * from goods where name="%s"' % find_name # Execute sql statement count = cur.execute(sql) # Get the result of the query result = cur.fetchall() # Print the result of the query print(result)

#
Close

the
Cursor

object
cur.close

(
) #

Close the Connection object conn.close ( )









Notice:

When entering the product name, enter

 
 
 
 

# Double quotes should also be entered
" or 1=1 or "

This completes a simple SQL injection

 
 
 
 

# Original sql statement
sql = 'select * from goods where name="%s"' % find_name
# Enter sql statement after " or 1=1 or "
sql = 'select * from goods where name="" or 1=1 or ""'

Here name= "" or 1=1 or "" is a condition that must be established, because or means or that multiple conditions are established as long as one condition is established, and 1=1 must be established. This causes the meaning of this SQL statement to change.

3. SQL statements in safe mode

 
 
 
 

fetchall() # print the result of the query





























print(result)

# Close the Cursor object
cur.close()

# Close the Connection object
conn.close()

Preventing SQL injection can be done using parameterized lists.

Summarize

SQL injection problem

  • Pass all the data parameters of the SQL statement in a list to the second parameter of the execute function

foreign key usage

learning target:

  • Know the role of database table foreign key constraints

  • Ability to add foreign key constraints to existing tables

  • Ability to add foreign key constraints when creating tables

1. Foreign keys

picture

Let's start to verify the role of foreign keys

  • Insert records in the goods_cates and goods_brands tables respectively

 
 
 
 

insert into goods_cates(name) values ​​('router'),('switch'),('network card');
insert into goods_brands(name) values ​​('Haier'),('Tsinghua Tongfang'),('Shenzhou');

  • Write any record in the goods data table

picture

 
 
 
 

insert into goods (name,cate_id,brand_id,price)
values('LaserJet Pro P1606dn black and white laser printer', 12, 4,'1849');

Question: What does 12 in the SQL statement mean? Yes, it is cate_id Excuse me: Is there a record with id=12 in the goods_cates table? Obviously not

picture

  • Query the detailed information of all commodities (add the data not displayed in the left table to the final result through left join)

 
 
 
 

select * from goods left join goods_cates on goods.cate_id = goods_cates.id;

Problem found: The data inserted by the SQL statement name of cate_id = 12 is problematic.

picture

How to prevent the insertion of invalid information, is it possible to determine whether the type or brand name exists before inserting? It can be solved by using the foreign key mentioned before

  • Foreign key constraint: The value of the foreign key field is compared with the field data in the referenced table when updating and inserting

  • Keyword: foreign key, only the innodb database engine supports foreign key constraints

2. Add foreign key constraints to existing fields

 
 
 
 

-- 给brand_id 添加外键约束和goods_brands的id建立外键关联
alter table goods add foreign key (brand_id) references goods_brands(id);
-- 给cate_id 添加外键约束和goods_cates的id建立外键关联
alter table goods add foreign key (cate_id) references goods_cates(id);

-- ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`jing_dong`.`#sql-403_5`, CONSTRAINT `#sql-403_5_ibfk_2` FOREIGN KEY (`cate_id`) REFERENCES `goods_cates` (`id`))

-- 给cate_id 添加外键失败
-- 会出现1452错误
-- 错误原因:已经添加了一个不存在的cate_id值12,因此需要先删除

delete from goods where cate_id = 12;
alter table goods add foreign key (cate_id) references goods_cates(id);

picture

  • At this time, if you insert a product of a non-existent brand (cate_id=12) again, an error will be reported

 
 
 
 

insert into goods (name,cate_id,brand_id,price) values('LaserJet Pro P1606dn black and white laser printer', 12, 4,'1849'); The insertion fails, and the error is as follows: ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`jing _dong`.`goods`, CONSTRAINT `goods_ibfk_2` FOREIGN KEY (`cate_id`) REFERENCES `goods_cates` (`id`

)
)

picture

3. Set foreign key constraints when creating a data table

  • Note: The type of cate_id in goods must be consistent with the type of id in the goods_cates table

 
 
 
 

create table goods(
id int primary key auto_increment not null,
name varchar(40) default '',
price decimal(5,2),
cate_id int unsigned,
brand_id int unsigned,
is_show bit default 1,
is_saleoff bit default 0,
foreign key(cate_id) references goods_cates(id),
foreign key(brand_id) references goods_brands(id)
);

4. Remove foreign key constraints

 
 
 
 

-- You need to get the name of the foreign key constraint first, the name will be automatically generated by the system, you can get the name by viewing the table creation statement show create
table goods;

-- After getting the name, you can delete the foreign key constraint according to the name
alter table goods drop foreign key foreign key name;

  • The use of foreign key constraints will greatly reduce the efficiency of table updates, so foreign keys are generally rarely used in scenarios where read and write efficiency is prioritized.

Summarize

  • Insert the queried data directly into the table  

 
 
 
 

insert into xxx (field name) select statement
Insert the result set of the select statement into a table

  • Link table update

 
 
 
 

update table 1 join table 2 on connection condition
set a table. field = value

  • foreign key constraints    

When inserting and updating new values ​​for foreign key fields in the subtable, the new value must have appeared in the corresponding field in the main table.

ER model and relationship between tables

learning target

  • Understand the components of the ER model

  • Be able to give examples of 1-to-1, 1-to-many-to-many relationship in life

1. ER model

  • Introduction to ER Model

The ER model is the ER diagram.

The ER diagram is an entity-relationship diagram (Entity Relationship Diagram), which provides a method for representing entity types, attributes and connections, and is used to describe the conceptual model of the real world. Invented by Chinese-American computer scientist Peter Chen.

  • ER model usage scenarios

  • Based on the relational model of the relational database, we need to extract the model and relationship according to the design plan of the product manager, and formulate the table structure. This is the first step in the project

  • In the design phase, ER models are generally used for modeling. There are many softwares for designing databases, commonly used such as power designer, db desinger, etc. These software can visually see the relationship between entities and entities

  • Designing the database may be done by a dedicated database designer, or by a member of the development team. Usually, the project manager leads the team to complete it

  • After the design is completed, the ER model will be converted into a relational model

picture

  • ER model components

picture

The ER diagram uses the three concepts of entity, connection and attribute to describe the real problem, and has the following three elements:

  • Entity: Entities with the same attributes have the same characteristics and properties. The entity name and its attribute name collection are used to abstract and describe similar entities; it is represented by a rectangle in the ER diagram, and the entity name is written in the rectangle box; for example, users, shopping carts, orders, etc. in the e-commerce shopping system are all entities.

  • Attribute: A certain characteristic of an entity. An entity can be characterized by several attributes. In the ER diagram, it is represented by an ellipse, and it is connected with the corresponding entity by an undirected edge; for example, the user's ID, user name, password, nickname, and ID number are all attributes.

  • Relationship: The way entities are connected to each other is called a relationship, also known as a relationship.

 
 
 
 

Entity: Represented by a rectangle and marked with the entity name

Attribute: Represented by an ellipse and marked with the name of the attribute Relationship

: Represented by a diamond and marked with the name of the relationship

Contacts can be divided into the following 3 types: one-to-one, one-to-many, many-to-many:

  • A relationship is also a kind of data, which needs to be stored in a table through a field

  • Entity A is 1 to 1 to entity B, then create a field in table A or table B to store the primary key value of the other table

picture

  • Entity A is 1-to-many to entity B: create a field in table B to store the primary key value of table A

picture

  • Entity A is many-to-many to entity B: create a new table C, this table has only two fields, one is used to store the primary key value of A, and the other is used to store the primary key value of B

picture

Summarize

  • A paradigm is a general specification for designing a database.

  • The ER diagram is composed of entities, attributes, and connections between entities, and is mainly used to describe the table structure in the database.

Guess you like

Origin blog.csdn.net/Blue92120/article/details/131822129