DML SQL 语句

DML SQL 语句

1,插入数据

使用INSERT向表中插入数据。格式为INSERT INFO table_name (COLUMN_NAME[,COLUMN_NAME]) VALUES (‘value’[,’value’]) 例如

insert into tb_test (name,birthday,sex) values ('榴莲','1990-01-01','');

值必须使用单引号引起来。当列的类型为数值类型时,单引号可以省略。值必须与前面的列一一对应。

2,查询数据

查询数据库使用SELECT命令。最简单的格式为:SELECT column_name from table_name.

如果查询多个列名使用逗号隔开。星号*”代表查询所有列。例如

Select * from tb_test;

Select id,name,description from tb_test;

扫描二维码关注公众号,回复: 1098186 查看本文章

也可以这样完整地写:

Select tb_test.* from databaseWeb.tb_test;

Select tb_test.id, tb_test.name,tb_test.description from databaseWeb.ta_test;

使用AS可以为列或者表重命名。AS关键字也可以省略,例如:

Select id as p_id, name as p_name from tb_test as test;

Select id p_id , name p_name from tb_test test;

注意:列的重命名只发生在结果集中,并不会对数据表产生任何作用。

Select语句后面跟where子句,表示有选择地显示数据。常用的条件有大于”>”,小于<”,等于“=”,不等于“<>”等。多个条件时,使用and(并且)or(或者)。字符类型数据必须使用单引号(‘),数据类型单引号可以省略,例如:

Select * from tb_test where id > 100;

Select * from tb_test where id > 100 and id <> 200;

Select * from tb_test where tb_test where id = 200;

Select * from tb_test where name = ‘张三’;

Where 中还可以使用like与“%”对字符类型的列进行模糊查询,例如:

Select * from tb_test where name like ‘%’;  --检索name列以’四’结尾的记录

Select * from tb_test where name like ‘%’;   --检索name列以’李’开头的记录

Select * from tb_test where name like ‘%%’   --检索name列包含三的记录

如果逻辑顺序有先后顺序,可以使用括号()括起来。Where子句执行的时候会先执行括号里的条件,后执行外面的条件,例如:

Select * from tb_test where ( salary >2000 and salary < 500) and (name like ‘%’ or name like ‘%’);

3,删除数据

使用delete 删除数据。例如,只删除id1的数据行:

Delete from tb_test where id=1;

4,修改数据

使用update修改数据。例如,只修改id2的数据行:

Update tb_test set birthday = ‘1991-01-02’ where id=2;

5,创建,删除,授权用户

MySQL数据库下使用create user 创建新用户,例如:

Create user helloweenvsfei;

新创建的用户没有任何授权。使用grant命令授权helloweenvsfei访问数据库databaseWeb下的所有表,密码为password123

Grant all privileges on databaseWeb.* to helloweenvsfei@’% ’ identified by ‘password123’ with grent option;

删除用户使用drop user命令。如:

Drop user helloweenvsfei;

6,批量执行SQL语句

SQL语句比较多时,通常将SQL语句写到.sql格式的文件中,使用批量的方式执行。下面是包含4sql语句的文件init.sql

Create table tb_category (

Id integer ,

Name varchar (50),

Description varchar(100),

Deleted integer,

Allowed_anonymous integer,

Need_project_info integer,

Primary key(id)

);

Insert into tb_category ( id, name,description,deleted,allowed_anonymous,need_project_info) values (1, ‘news’, ‘ ’,0,1,0);

Insert into tb_category (id, name,description,deleted,allowed_anonymous,need_project_info) values (2,’download’,’ ’ , 0,0,1);

SQL语句之间使用分号“;”隔开。“--”引起的行是注释行。

使用命令source”或者反斜杠加点“\.”在控制台执行SQL文件,例如:

MySQL> \. C:\init.sql

Mysql> Source c:\init.sql

猜你喜欢

转载自blog.csdn.net/lyue4/article/details/75349119