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. 開啟服務:net start mysql(mysql為配置時,可自定名稱)
2.關閉服務:net stop mysql
3.從cmd 模式進入mysql
(1).mysql -u 使用者名稱 -p 回車>輸入正確密碼>進入歡迎
(2).mysql -h IP(本機localhost) -u 使用者名稱 -p 回車>輸入正確密碼>進入歡迎
3.退出:exit/quit;
4.修改使用者密碼:mysqladmin -u 使用者名稱 -p password 新密碼
5、增加一個管理員帳戶:grant all on *.* to [email protected] identified by "password";
二、增刪改查語句
- 顯示資料表字段:describe 表名;
- 當前庫資料表結構:show tables;
- ALTER TABLE [表名] ADD COLUMN [欄位名] DATATYPE
- ALTER TABLE [表名] ADD PRIMARY KEY ([欄位名]) 說明:更改表得的定義把某個欄位設為主鍵。
- 新增:INSERT INTO [id,name...表名] VALUES('','' 王樂",......順序排列的資料); 或者:insert into 表名(id,name) values(0,'尹當')
- 刪除:DELETE FROM [表名] WHERE ([條件]); 刪除表中的列:alter table 表名 drop column 列名;
- 修改:UPDATE [表名] SET [修改內容如name = 'Mary' 列名='新的值,非數字加單引號'] WHERE [條件如:id=3];
- 資料傳入命令 load data local infile "[檔名]" into table [表名];
- 分頁查詢:select *from 表名 limit 每頁數量 offset 偏移量;
- create table 表名(id int auto_increment primary key,name varchar(20)) DEFAULT CHARSET=gbk
- 新增主外來鍵:alter table 外表名 add constraint FK_名稱 foreign key(外列) references 主表名(主列)
如現有兩表 主表tbl_order 子表tbl_orderdetail 現子表tbl_orderdetail的oid列引用了主表tbl_order的oid列 則命令如下:
alter table tbl_orderdetail add constraint FK_oid foreign key(oid) references tbl_order(oid) ;
查詢時間:select now();
查詢當前使用者:select user();
查詢資料庫版本:select version();
查詢當前使用的資料庫:select database();
三、操作指令
1、刪除student_course資料庫中的students資料表:
rm -f student_course/students.*
2、備份資料庫:(將資料庫test備份)
mysqldump -u root -p test>c:\test.txt
備份表格:(備份test資料庫下的mytable表格)
mysqldump -u root -p test mytable>c:\test.txt
將備份資料匯入到資料庫:(導回test資料庫)
mysql -u root -p test
//
MYSQL資料庫匯入匯出匯入:mysql -uroot -ptian test<test.sql
匯出:mysqldump -uroot -ptian test>test.sql
其中 -uroot 表示使用者名稱
-ptian 表示密碼
test 表示資料庫名(已存在的)
test.sql 表示外部的指令碼檔案(檔名字、格式隨便,例如:a.sql,a.abc......)
3、建立臨時表:(建立臨時表zengchao)
create temporary table zengchao(name varchar(10));
4、複製表: create table table2 select * from table1;
5、對錶重新命名 alter table table1 rename as table2;
6、修改列的型別
alter table table1 modify id int unsigned;//修改列id的型別為int unsigned
alter table table1 change id sid int unsigned;//修改列id的名字為sid,而且把屬性修改為int unsigned
7、建立索引 alter table table1 add index ind_id (id);
8、聯合字元或者多個列(將列id與":"和列name和"="連線)
select concat(id,':',name,':',age) as 學生年齡 from students;
9、增加一個使用者test2密碼為abc,讓他只可以在localhost上登入,並可以對資料庫mydb進行查詢、插入、修改、刪除的操作
grant select,insert,update,delete on mydb.* to [email protected] identified by \"abc\"; 如果希望該使用者能夠在任何機器上登陸mysql,則將localhost改為"%"。