创建和选择数据库
创建menagerie数据库:
mysql> CREATE DATABASE menagerie;
如果想在创建数据库时,指定数据库的字符编码(这里使用GBK),可以使用以下方式:
mysql> create database menagerie DEFAULT CHARACTER SET gbk COLLATE gbk_chinese_ci;
或者使用utf8编码:
mysql> CREATE DATABASE menagerie DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
或者直接修改配置文件:
hadoop@node1:~/mysql_shell$ sudo vi /etc/mysql/my.cnf
然后在文件底部加入以下内容:
[mysqld]
character-set-server=utf8
collation-server=utf8_general_ci
接着重启MySQL服务
hadoop@node1:~/mysql_shell$ sudo service mysql stop
hadoop@node1:~/mysql_shell$ sudo service mysql start
通过status命令可以查看状态信息:
mysql> status
--------------
mysql Ver 14.14 Distrib 5.7.13, for Linux (x86_64) using EditL ine wrapper
Connection id: 3
Current database: eduCloud
Current user: root@localhost
SSL: Not in use
Current pager: stdout
Using outfile: ''
Using delimiter: ; Server version: 5.7.13-0ubuntu0.16.04.2 (Ubuntu)
Protocol version: 10
Connection: Localhost via UNIX socket
Server characterset: utf8
Db characterset: utf8
Client characterset: utf8
Conn. characterset: utf8
UNIX socket: /var/run/mysqld/mysqld.sock
Uptime: 9 min 25 sec
Threads: 1 Questions: 62 Slow queries: 0 Opens: 128 Flush tables: 1 Open tables: 47 Queries per second avg: 0.109
--------------
创建表
创建pet表,包含:宠物名字,拥有者,物种,性别,出生日期,死亡日期:
mysql> CREATE TABLE pet (name VARCHAR(20), owner VARCHAR(20),
-> species VARCHAR(20), sex CHAR(1), birth DATE, death DATE);
一旦你创建了表,你可以查看刚刚创建的表是否是想创建的表
mysql> SHOW TABLES;
+---------------------+
| pet | |
+---------------------+
mysql> DESCRIBE pet;
+---------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra | |
+---------+-------------+------+-----+---------+-------+
| name | varchar(20) | YES | | NULL | | |
| owner | varchar(20) | YES | | NULL | | |
| species | varchar(20) | YES | | NULL | | |
| sex | char(1) | YES | | NULL | | |
| birth | date | YES | | NULL | | |
| death | date | YES | | NULL | | |
+---------+-------------+------+-----+---------+-------+
可以看到表pet的字段,类型,等数据。
我们也可以通过脚本的方式进行创建表,在一个文件中写创建表的脚本,然后在 mysql>中使用source命令或.运行,如下:
mysql> source ./testCreateTable.txt;
Database changed
Query OK, 0 rows affected, 1 warning (0.00 sec)
Query OK, 0 rows affected (0.24 sec)
其中,testCreateTable.txt是脚本文件,内容如下:
use test
drop table if exists testTable;
create table testTable(name varchar(50),
address varchar(50),
timestamp timestamp,
primary key(name));