[Development experience] mysql effectively prevents the database from being deleted and running away!


You must have heard that due to personal mistakes, some developers did not add a where statement to the delete or update statement, resulting in confusion in the entire table data.

MySQL security mode: MySQL will report an error when it finds that the delete and update statements do not add where or limit conditions. The entire sql will not be executed, effectively preventing the accidental deletion of tables.

Safe Mode Settings

Check the status with the following command in mysql:

 show variables like 'sql_safe_updates';

insert image description here

The default is OFF state, you can set the state to ON:

  • set sql_safe_updates=1;//Open
  • set sql_safe_updates=0;//closure

After set to ON

  • Update statement : When no index is available for the column (column) in the where condition and there is no limit limit, the update will be rejected. When the where condition is constant and there is no limit, the update will be rejected.
  • delete statement: ① where condition is constant, ② or where condition is empty, ③ or where no index is available for the column (column) and there is no limit to refuse to delete.

test

Open safe mode to test

1. Update and delete without where

delete from t_user

delete from t_user
> 1175 - You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column
> 时间: 0.001s

update t_user set name='123'

update t_user set name='123'
> 1175 - You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column
> 时间: 0.001s

2. Delete of non-index keys

delete from t_user where name='123'

delete from  t_user where name='123'
> 1175 - You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column
> 时间: 0.007s

If the where condition of delete is not an index key, you must add limit.

delete from t_user where name='123' limit 1

delete from  t_user where name='123' limit 1
> Affected rows: 0
> 时间: 0.002s

3. delete the index key

delete from t_user where group_id='123'

delete from  t_user where group_id='123'
> Affected rows: 0
> 时间: 0s

Summarize

If set sql_safe_updates=1, the updatestatement must meet one of the following conditions to execute successfully

  1. Use the where clause, and the column in the where clause must be the prefix index column
  2. use limit
  3. Use where clause and limit at the same time (the column in the where clause may not be an index column at this time)

deleteThe statement must meet one of the following conditions to execute successfully

  1. Use the where clause, and the column in the where clause must be the prefix index column
  2. Use the where clause and limit at the same time (the column in the where clause may not be an index column at this time)
    to execute successfully.

Guess you like

Origin blog.csdn.net/qq_30285985/article/details/120525460