MySQL数据库之DML(数据操作语言)

对表记录的增删改

1.MySQL之DML创建数据表user

create table user(
id int unsigned not null auto_increment primary key,
user_name varchar(20) not null,
password char(32) not null,
email varchar(50) not null,
mobile char(11) not null,
fee decimal(10,2) not null default 0.00,
age tinyint(3) unsigned not null
);

查user表中的数据:

select * from user;

2.MySQL之DML插入数据库的几种方法

insert into 表名(列1,列2,......) values(列值1,列值2,......);其中,列和值是一一对应的;

法一:insert into user(user_name,password,email,mobile,fee,age) values('jack',md5('123456'),'jack@163.com','13045678911',123.11,29);
法二:insert into user(user_name,email) values('jack','jack@163.com');
法三:insert into user values(3,'jack2',md5('1234562'),'jack2@163.com','13045678900',13.01,25);

注意:

(1)如果sql_mode设置为STRICT_TRANS_TABLE,方法二会出错,因为在该模式下,如果一个值不能插入到一个事务表中,则中断当前的操作,对非事务表不做任何限制,即该模式下为严格模式。具体可看:MySQL的sql_mode解析与设置ERROR 1364 (HY000): Field '***' doesn't have a default value 解决方法

(2)最新版的MySql移除了password函数MySQL数据库内置加密函数总结

3.MySQL之DML插入汉字乱码的解决方法

4.MySQL之DML数据的更新

update 表名 set lie1=列值1,列2=列值2 where 条件;

注意,不加where条件会修改所有的记录

修改前的user表:

(1)执行以下更新命令后:

update user set age=50 where id=2;

user表更新成:

(2)执行以下更新命令后:

update user set fee=11.10 where fee=0.00;

user表更新成:

(3)执行以下更新命令后:

update user set user_name='zhang' where user_name!='lidehua';

user表更新成:

(4)执行以下更新命令后:

update user set email='hehe@163.com' where email='';

user表更新成:

(5)执行以下更新命令后:

update user set user_name='wang' where id in(1,3);

user表更新成:

(6)执行以下更新命令后:

update user set mobile='88888888888' where id between 2 and 3;

user表更新成:

(7)执行以下更新命令后:

update user set password=md5('456789'),mobile='13078945612',age=41 where id=3;

user表更新成:

 5.MySQL之DML数据的删除

(1)delete from 表名 where 条件;注意:不加where会删除所有的记录

(2)truncate 表名;注:是DDL的

区别:

truncate将表清空了,插入数据时id会从头开始排;用delete删除整个表或者某一行数据,删除的id值仍被占用,插入数据时,id会紧接着删掉的id值进行递增;

truncate适用于删除垃圾数据;

原文地址:https://www.cnblogs.com/yuehouse/p/11183995.html