您的位置:首页 > 数据库 > MySQL

mysql笔记_158281924

2015-08-28 19:40 776 查看
mysql -h 主机名 -u 用户名 -p

  -h : 该命令用于指定客户端所要登录的MySQL主机名, 登录当前机器该参数可以省略;

  -u : 所要登录的用户名;

  -p : 告诉服务器将会使用一个密码来登录, 如果所要登录的用户名密码为空, 可以忽略此选项

create database samp_db character set gbk;

为了便于在命令提示符下显示中文, 在创建时通过 character set gbk 将数据库字符编码指定为 gbk

选择所要操作的数据库

  一: 在登录数据库时指定, 命令: mysql -D 所选择的数据库名 -h 主机名 -u 用户名 -p

  二: 在登录后使用 use 语句指定, 命令: use 数据库名;

创建数据库表

  create table 表名称(列声明);

  

create table students
(
id int unsigned not null auto_increment primary key,
name char(8) not null,
sex char(4) not null,
age tinyint unsigned not null,
tel char(13) null default "-"
);

可以通过任何文本编辑器将语句输入好后保存为 createtable.sql 的文件中, 通过命令提示符下的文件重定向执行执行该脚本。

打开命令提示符, 输入: mysql -D samp_db -u root -p < createtable.sql

语句解说:

以 "id int unsigned not null auto_increment primary key" 行进行介绍:

  "id" 为列的名称;

  "int" 指定该列的类型为 int(取值范围为 -8388608到8388607), 在后面我们又用 "unsigned" 加以修饰, 表示该类型为无符号型, 此时该列的取值范围为 0到16777215;

  "not null" 说明该列的值不能为空, 必须要填, 如果不指定该属性, 默认可为空;

  "auto_increment" 需在整数列中使用, 其作用是在插入数据时若该列为 NULL, MySQL将自动产生一个比现存值更大的唯一标识符值。在每张表中仅能有一个这样的值且所在列必须为索引列。

  "primary key" 表示该列是表的主键, 本列的值必须唯一, MySQL将自动索引该列。

向表中插入数据

  insert into students values(NULL, "王刚", "男", 20, "13811371377");

查询表中的数据

mysql> select name, age from students;

按特定条件查询

select 列名称 from 表名称 where 条件;

where 子句不仅仅支持 "where 列名 = 值" 这种名等于值的查询形式, 对一般的比较运算的运算符都是支持的, 例如 =、>、<、>=、<、!= 以及一些扩展运算符 is [not] null、in、like 等等

示例:

查询年龄在21岁以上的所有人信息: select * from students where age > 21;

查询名字中带有 "王" 字的所有人信息: select * from students where name like "%王%";

查询id小于5且年龄大于20的所有人信息: select * from students where id<5 and age>20;

更新表中的数据

  update 表名称 set 列名称=新值 where 更新条件;

  

  将id为5的手机号改为默认的"-": update students set tel=default where id=5;

  将所有人的年龄增加1: update students set age=age+1;

  将手机号为 13288097888 的姓名改为 "张伟鹏", 年龄改为 19: update students set name="张伟鹏", age=19 where tel="13288097888";

删除表中的数据

  delete from 表名称 where 删除条件;

  

  使用示例:

  删除id为2的行: delete from students where id=2;

  删除所有年龄小于21岁的数据: delete from students where age<20;

  删除表中的所有数据: delete from students;

创建后表的修改

  alter table 语句用于创建后对表的修改, 基础用法如下:

添加列

基本形式: alter table 表名 add 列名 列数据类型 [after 插入位置];

示例:

在表的最后追加列 address: alter table students add address char(60);

修改列

基本形式: alter table 表名 change 列名称 列新名称 新数据类型;

示例:

将表 tel 列改名为 telphone: alter table students change tel telphone char(13) default "-";

删除列

基本形式: alter table 表名 drop 列名称;

示例:

删除 birthday 列: alter table students drop birthday;

重命名表

基本形式: alter table 表名 rename 新表名;

示例:

重命名 students 表为 workmates: alter table students rename workmates;

删除整张表

基本形式: drop table 表名;

示例: 删除 workmates 表: drop table workmates;

删除整个数据库

基本形式: drop database 数据库名;

示例: 删除 samp_db 数据库: drop database samp_db;

修改 root 用户密码

使用 mysqladmin 方式:

打开命令提示符界面, 执行命令: mysqladmin -u root -p password 新密码
http://www.cnblogs.com/mr-wid/archive/2013/05/09/3068229.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: