MySQL学习笔记2

基本操作

列出和创建数据库

列出数据库

同样要先进MySQL的交互界面,执行:

Use the SHOW statement to find out what databases currently exist on the server:

SHOW DATABASES;

输出大致如下:

+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| wesley09202016 |
| wesley09212016 |
+--------------------+
5 rows in set (0.00 sec)

The mysql database describes user access privileges.

另外,可以看到我新建的2个数据库。

新建数据库

现在新建一个数据库:

CREATE DATABASE wesleytest;
Query OK, 1 row affected (0.02 sec)

选择这个新建的数据库并使用:

USE wesleytest;
Database changed

操作数据库,列出并新建表

Creating the database is the easy part, but at this point it is empty, as SHOW TABLES tells you:

SHOW TABLES;
Empty set (0.00 sec)

新建表:

CREATE TABLE student(name VARCHAR(20), sex CHAR(1), birth DATE);
Query OK, 0 rows affected (0.18 sec)

查看结果:

SHOW TABLES;

现在输出是:

+----------------------+
| Tables_in_wesleytest |
+----------------------+
| student |
+----------------------+
1 row in set (0.00 sec)

To verify that your table was created the way you expected, use a DESCRIBE statement:

DESCRIBE student;

输出:

+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| name | varchar(20) | YES | | NULL | |
| sex | char(1) | YES | | NULL | |
| birth | date | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

表明新建表成功。

对表中的数据进行增删查改

数据库中的数据以表的形式存储,任何数据的增删查都以表为单位。

增加数据

使用INSERT

INSERT INTO student 
VALUES ('Bob','m','1999-03-30');

使用LOAD DATA:

LOAD DATA LOCAL INFILE '/path/pet.txt' INTO TABLE pet;

上面的语句可以将pet.txt中的内容添加到表pet中。但是本机运行中出现以下错误提示:

ERROR 1148 (42000): The used command is not allowed with this MySQL version.

资料得出结论,本机使用的MySQL在编译安装时没有指定–enable-local-infile,解决方案有两种:

  1. 重新编译安装加上上面的参数
  2. 直接在Shell下用命令行执行

第二种更方便一些,在Shell下执行:

mysql -uroot -proot  mydb_name --local-infile=1 -e 'load data local infile "D:/ab.txt" into table mytbl(name,age)'

采用这种方式,处理表student,可以看到处理后的表中添加了预先写好的txt内容,即表示成功。

查看表中数据

The SELECT statement is used to pull information from a table. The general form of the statement is:

SELECT * FROM student;

输出会显示刚才添加的记录:

+------+------+------------+
| name | sex | birth |
+------+------+------------+
| Bob | m | 1999-03-30 |
+------+------+------------+
1 row in set (0.00 sec)

修改数据

Fix only the erroneous record with an UPDATE statement:

UPDATE student SET birth = '1989-08-31' WHERE name = 'Bob';
Query OK, 1 row affected (0.14 sec)
Rows matched: 1 Changed: 1 Warnings: 0

输出显示更改后的数据:

+------+------+------------+
| name | sex | birth |
+------+------+------------+
| Bob | m | 1989-08-31 |
+------+------+------------+
1 row in set (0.00 sec)

另一种方式是删掉现在表中的内容,然后修改之前生成表使用的txt,再将txt重新导入生成这张表:

DELETE FROM pet;
LOAD DATA LOCAL INFILE '/path/pet.txt' INTO TABLE pet;

官网给出的方法只有这两种。