1. 程式人生 > 實用技巧 >mysql常用語句、命令(增刪改查功能)

mysql常用語句、命令(增刪改查功能)

修改資料庫的字符集
mysql>use mydb
mysql>alter database mydb character set utf8;
建立資料庫指定資料庫的字符集
mysql>create database mydb character set utf8;

檢視database的字符集!

show variables like 'collation_%';
show variables like 'character_set_%';

一、系統操作

1.開啟服務:netstartmysql(mysql為配置時,可自定名稱)

2.關閉服務:netstopmysql

3.從cmd模式進入mysql

(1).mysql-u使用者名稱-p回車>輸入正確密碼>進入歡迎

(2).mysql-hIP(本機localhost)-u使用者名稱-p回車>輸入正確密碼>進入歡迎

3.退出:exit/quit;

4.修改使用者密碼:mysqladmin-u使用者名稱-ppassword新密碼

5、增加一個管理員帳戶:grantallon*.*touser@localhostidentifiedby"password";

二、增刪改查語句
  1. 顯示資料表字段:describe表名;
  2. 當前庫資料表結構:showtables;
  3. ALTERTABLE[表名]ADDCOLUMN[欄位名]DATATYPE
  4. ALTERTABLE[表名]ADDPRIMARYKEY([欄位名]) 說明:更改表得的定義把某個欄位設為主鍵。
  5. 新增:INSERTINTO[id,name...表名]VALUES('','' 王樂",......順序排列的資料); 或者:insertinto表名(id,name)values(0,'尹當')
  6. 刪除:DELETEFROM[表名]WHERE([條件]); 刪除表中的列:altertable表名dropcolumn列名;
  7. 修改:UPDATE[表名]SET[修改內容如name='Mary'列名='新的值,非數字加單引號']WHERE[條件如:id=3];
  8. 資料傳入命令loaddatalocalinfile"[檔名]"intotable[表名];
  9. 分頁查詢:select*from表名limit每頁數量offset偏移量;
  10. createtable表名(idintauto_incrementprimarykey,namevarchar(20))DEFAULTCHARSET=gbk
  11. 新增主外來鍵:altertable外表名addconstraintFK_名稱foreignkey(外列)references主表名(主列)

如現有兩表主表tbl_order子表tbl_orderdetail現子表tbl_orderdetail的oid列引用了主表tbl_order的oid列 則命令如下:

  altertabletbl_orderdetailaddconstraintFK_oidforeignkey(oid)referencestbl_order(oid) ;

查詢時間:selectnow();

查詢當前使用者:selectuser();

查詢資料庫版本:selectversion();

查詢當前使用的資料庫:selectdatabase();

三、操作指令

1、刪除student_course資料庫中的students資料表:

rm-fstudent_course/students.*

2、備份資料庫:(將資料庫test備份)

mysqldump-uroot-ptest>c:\test.txt

備份表格:(備份test資料庫下的mytable表格)

mysqldump-uroot-ptestmytable>c:\test.txt

將備份資料匯入到資料庫:(導回test資料庫)

mysql-uroot-ptest

//

MYSQL資料庫匯入匯出

匯入:mysql -uroot -ptian test<test.sql
匯出:mysqldump -uroot -ptian test>test.sql

其中 -uroot 表示使用者名稱

   -ptian 表示密碼

   test 表示資料庫名(已存在的)

   test.sql 表示外部的指令碼檔案(檔名字、格式隨便,例如:a.sql,a.abc......)

3、建立臨時表:(建立臨時表zengchao)

createtemporarytablezengchao(namevarchar(10));

4、複製表:createtabletable2select*fromtable1;

5、對錶重新命名 altertabletable1renameastable2;

6、修改列的型別

altertabletable1modifyidintunsigned;//修改列id的型別為intunsigned

altertabletable1changeidsidintunsigned;//修改列id的名字為sid,而且把屬性修改為intunsigned

7、建立索引 altertabletable1addindexind_id(id);

8、聯合字元或者多個列(將列id與":"和列name和"="連線)

selectconcat(id,':',name,':',age) as 學生年齡 fromstudents;

9、增加一個使用者test2密碼為abc,讓他只可以在localhost上登入,並可以對資料庫mydb進行查詢、插入、修改、刪除的操作

grantselect,insert,update,deleteonmydb.*totest2@localhostidentifiedby\"abc\"; 如果希望該使用者能夠在任何機器上登陸mysql,則將localhost改為"%"。