MySQL中庫、表創建需注意事項

MySQL中,我們在創建庫和表時,會有一些疏忽,造成錯誤難以檢查。

我創建了一個名爲python3的數據庫以及名爲students的表,數據庫如下:

mysql> SHOW CREATE DATABASE python3;
+----------+------------------------------------------------------------------+
| Database | Create Database                                                  |
+----------+------------------------------------------------------------------+
| python3  | CREATE DATABASE `python3` /*!40100 DEFAULT CHARACTER SET utf8 */ |
+----------+------------------------------------------------------------------+
1 row in set (0.00 sec)

但是我們想顯示創建表信息,卻出現如下錯誤:

mysql> SHOW CREATE TABLE students;

ERROR 1046 (3D000): No database selected

出現這種情況是因爲沒有切換到當前數據庫,應該加上use python3:

mysql> use python3;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A


Database changed

這時已經切換到當前數據庫了。

關於創建表的信息:

# students中有四個參數:number(文本格式,9位);name(可變文本,最高20位),
# age(整型);birthDATE時間格式)
CREATE TABLE students(
    number CHAR(9),
    name VARCHAR(20),
    age INT,
    birth DATE
);
在表格裏添加信息,三種方式:

INSERT INTO students(number,name,age) VALUES('201812101','吳彥祖',26); #三個參數,缺少的一個會用null補上
INSERT INTO students VALUES('201812102','陳冠希',25,'1989-11-11');  #四個參數
INSERT INTO students VALUES('201812103','吳磊',19,'1995-10-01'),('201812104','張學友',40,'1980-11-12'),('201812105','陳奕迅',37,'1988-12-09');
執行結果:

mysql> SELECT * FROM students;
+-----------+-----------+------+------------+
| number    | name      | age  | birth      |
+-----------+-----------+------+------------+
| 201812101 | 吳彥祖    |   26 | NULL       |
| 201812102 | 陳冠希    |   25 | 1993-10-19 |
| 201812103 | 吳磊      |   19 | 1995-10-01 |
| 201812104 | 張學友    |   40 | 1980-11-12 |
| 201812105 | 陳奕迅    |   37 | 1988-12-09 |
+-----------+-----------+------+------------+

5 rows in set (0.04 sec)

增加表格信息時,除了第一個方法可以少賦值參數,其他兩種都得一一對應。DATE的格式是:'1993-10-19',注意有'-'。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章