MySql數據庫經常使用命令整理

1.登錄mysql:
    mysql -h 主機名 -u 用戶名 -p 密碼mysql

2.建立數據庫
    create database 數據庫名 //create database my_sql
    
3.選擇所要操做的數據庫
    (1).在登陸數據庫時指定, 命令: mysql -D 所選擇的數據庫名 -h 主機名 -u 用戶名 -p
        例如登陸時選擇剛剛建立的數據庫: mysql -D samp_db -u root -psql

    (2). 在登陸後使用 use 語句指定, 命令: use 數據庫名;
        use 語句能夠不加分號, 執行 use samp_db 來選擇剛剛建立的數據庫, 選擇成功後會提示: Database changed數據庫

4.建立數據庫表
    create table 表名稱(列聲明);
    
5.向表中插入數據
    insert 語句能夠用來將一行或多行數據插到數據庫表中, 使用的通常形式以下:
    insert [into] 表名 [(列名1, 列名2, 列名3, ...)] values (值1, 值2, 值3, ...);
    insert into students values(NULL, "王剛", "男", 20, "13811371377");
    
6.查詢表中的數據
    select 列名稱 from 表名稱 [查詢條件]
    例如要查詢 students 表中全部學生的名字和年齡, 輸入語句 select name, age from students; 
    也能夠使用通配符 * 查詢表中全部的內容, 語句: select * from students;
    
7.按特定條件查詢
    where 關鍵詞用於指定查詢條件:select 列名稱 from 表名稱 where 條件
    示例:
        查詢年齡在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;
        
8.更新表中的數據
    update語句可用來修改表中的數據: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";
    
9.刪除表中的數據
    delete 語句用於刪除表中的數據:delete from 表名稱 where 刪除條件
    示例:
        刪除id爲2的行: delete from students where id=2;
        刪除全部年齡小於21歲的數據: delete from students where age<20;
        刪除表中的全部數據: delete from students;
        
建立後表的修改
alter table 語句用於建立後對錶的修改, 基礎用法以下:table

1.添加列:alter table 表名 add 列名 列數據類型 [after 插入位置]
    實例:
        在表的最後追加列 address: alter table students add address char(60);
        在名爲 age 的列後插入列 birthday: alter table students add birthday date after age;
        
2.修改列:alter table 表名 change 列名稱 列新名稱 新數據類型
    實例:
        將表 tel 列更名爲 telphone: alter table students change tel telphone char(13) default "-";
        將 name 列的數據類型改成 char(16): alter table students change name name char(16) not null;
        
3.刪除列:alter table 表名 drop 列名稱
    示例:
        刪除 birthday 列: alter table students drop birthday;
    
4.重命名錶:alter table 表名 rename 新表名
    實例:重命名 students 表爲 workmates: alter table students rename workmates;
    
5.刪除整張表:drop table 表名稱
    實例:刪除 workmates 表: drop table workmates;
    
6.刪除整個數據庫:drop database 數據庫名;
    示例: 刪除 samp_db 數據庫: drop database samp_db;
    
7.修改 root 用戶密碼
    按照本文的安裝方式, root 用戶默認是沒有密碼的, 重設 root 密碼的方式也較多, 這裏僅介紹一種較經常使用的方式。
    使用 mysqladmin 方式:
        打開命令提示符界面, 執行命令: mysqladmin -u root -p password 新密碼
        執行後提示輸入舊密碼完成密碼修改, 當舊密碼爲空時直接按回車鍵確認便可。
    
    
    
    
    登錄

相關文章
相關標籤/搜索