MySQL 命令详细说明以及案例
2025-03-06
9
MySQL 命令详细说明及案例
1. 连接数据库
mysql -u username -p
-u
:指定用户名-p
:提示输入密码
案例:
mysql -u root -p
2. 创建数据库
CREATE DATABASE database_name;
案例:
CREATE DATABASE mydb;
3. 删除数据库
DROP DATABASE database_name;
案例:
DROP DATABASE mydb;
4. 选择数据库
USE database_name;
案例:
USE mydb;
5. 创建表
CREATE TABLE table_name ( column1 datatype, column2 datatype, ... );
案例:
CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) NOT NULL, email VARCHAR(100) NOT NULL );
6. 删除表
DROP TABLE table_name;
案例:
DROP TABLE users;
7. 插入数据
INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);
案例:
INSERT INTO users (username, email) VALUES ('john_doe', 'john@example.com');
8. 查询数据
SELECT column1, column2, ... FROM table_name WHERE condition;
案例:
SELECT * FROM users; SELECT username, email FROM users WHERE id = 1;
9. 更新数据
UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;
案例:
UPDATE users SET email = 'john_new@example.com' WHERE id = 1;
10. 删除数据
DELETE FROM table_name WHERE condition;
案例:
DELETE FROM users WHERE id = 1;
11. 创建索引
CREATE INDEX index_name ON table_name (column1, column2, ...);
案例:
CREATE INDEX idx_username ON users (username);
12. 删除索引
DROP INDEX index_name ON table_name;
案例:
DROP INDEX idx_username ON users;
13. 创建用户
CREATE USER 'username'@'host' IDENTIFIED BY 'password';
案例:
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';
14. 授予权限
GRANT permission_type ON database_name.table_name TO 'username'@'host';
案例:
GRANT ALL PRIVILEGES ON mydb.* TO 'newuser'@'localhost';
15. 撤销权限
REVOKE permission_type ON database_name.table_name FROM 'username'@'host';
案例:
REVOKE ALL PRIVILEGES ON mydb.* FROM 'newuser'@'localhost';
16. 查看表结构
DESCRIBE table_name;
案例:
DESCRIBE users;
17. 备份数据库
mysqldump -u username -p database_name > backup_file.sql
案例:
mysqldump -u root -p mydb > mydb_backup.sql
18. 恢复数据库
mysql -u username -p database_name < backup_file.sql
案例:
mysql -u root -p mydb < mydb_backup.sql
19. 查看当前数据库
SELECT DATABASE();
20. 查看所有数据库
SHOW DATABASES;
21. 查看所有表
SHOW TABLES;
22. 查看用户权限
SHOW GRANTS FOR 'username'@'host';
案例:
SHOW GRANTS FOR 'newuser'@'localhost';
23. 修改表结构
ALTER TABLE table_name ADD column_name datatype;
案例:
ALTER TABLE users ADD age INT;
24. 删除列
ALTER TABLE table_name DROP COLUMN column_name
本篇文章内容来源于:MySQL 命令详细说明以及案例
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。