標籤:
轉自:http://blog.163.com/[email protected]/blog/static/170171558201411311547655/
1、# 建立資料庫語句
create database mydb default character set utf8;
# 運用資料庫語句
use mydb;
# 建立表格,這裡只簡單的建立一張表格
# 設定InnoDB主要是為了事務操作的需要
create table mytable(
id int primary key auto_increment,
name varchar(20),
count int not null
)type=InnoDB;
# cmd進入資料庫方法
mysql -u root -p
#輸入密碼進入mysql命令列
#將以上sql語句放到.sql檔案中,並匯入資料庫,這裡是windows方式
#注意:這裡路徑不能添加引號,只需要直接放到source後即可,否則報錯
#source $path\mydb.sql
mysql> source E:\mydb.sql
Query OK, 1 row affected (0.00 sec)
Database changed
Query OK, 0 rows affected, 1 warning (0.09 sec)
#describe mytable或者desc mytable檢查表格欄位是否有誤
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(20) | YES | | NULL | |
| count | int(11) | NO | | NULL | |
+-------+-------------+------+-----+---------+----------------+
2、#向表格中匯入資料或者匯出資料
#首先採用.txt文本匯入方式
#按照表格欄位進行樣本如下:
id name count
1 張三 1000
2 李四 500
3 王老虎 100
#將三組資料複製放到建立txt文本中,這麼命名為:mydb.txt
mysql> load data infile ‘E:\mydb.txt‘ into table mytable
-> fields terminated by ‘\t‘ #表示欄位間距
-> lines terminated by ‘\n‘; #表示行間距
Query OK, 3 rows affected (0.03 sec)
Records: 3 Deleted: 0 Skipped: 0 Warnings: 0
#由於資料較少這裡通過簡單的查詢可以查看資料匯入資訊
mysql> select * from mytable;
+----+--------+-------+
| id | name | count |
+----+--------+-------+
| 1 | 張三 | 1000 |
| 2 | 李四 | 500 |
| 3 | 王老虎 | 100 |
+----+--------+-------+
3 rows in set (0.05 sec)
#由於Id欄位是自動增加的,所以這裡嘗試一下不添加欄位
#預編寫sql語句:load data local infile ‘E:\mydb.txt‘ into table mytable(name,count);
#匯入資料為:
趙大 1000
王二小 500
三亞子 100
mysql> load data local infile ‘E:\mydb.txt‘ into table mytable(name,count);
Query OK, 3 rows affected (0.07 sec)
Records: 3 Deleted: 0 Skipped: 0 Warnings: 0
#查詢新資料,這裡的方法只適合資料較小的情況
mysql> select * from mytable;
+----+--------+-------+
| id | name | count |
+----+--------+-------+
| 1 | 張三 | 1000 |
| 2 | 李四 | 500 |
| 3 | 王老虎 | 100 |
| 4 | 趙大 | 1000 |
| 5 | 王二小 | 500 |
| 6 | 三亞子 | 100 |
+----+--------+-------+
6 rows in set (0.00 sec)
#可以看到確實增加了三行資料,而且ID自增。
#這裡嘗試一下將表中資料匯出到txt檔案中,這裡我們有選擇的匯出資料,如果全部匯出與之類似
#下面方式會報錯
select * into outfile ‘E:\mydb1.txt‘
lines terminated by ‘\r\n‘
fields terminated by ‘\t‘
from mytable;
#這個地方有一個奇特的現象fields行必須添加到lines上面即如下操作才不會報錯:
mysql> select * into outfile ‘E:\mydb1.txt‘
-> fields terminated by ‘\t‘ #在此例中該行可有可無
-> lines terminated by ‘\r\n‘
-> from mytable ;
Query OK, 6 rows affected (0.00 sec)
#匯出資料並不包括表欄位。
mysql學習之通過檔案建立資料庫以及添加資料