MySQL 常用操作

2018-12-05  本文已影响4人  S大偉

MySQL 权限等级 由高到底

用户 --> 数据库 --> 表 -->列
user --> db --> tables --> columns

用户

#创建、删除、显示用户
mycursor.execute("create user if not exists testuser @'localhost' identified by '12345678'")
#drop user 用户名@'%';
mysql> drop user "test" @"localhost";
mysql> select user,host from mysql.user;

#登录退出
mysql -u 用户 -p
mysql> exit;

#显示权限
mysql> show grants;
mysql> show grants for testuser@localhost;

#授权
#grant 权限 on 数据库.表 to 用户名@登录主机 identified by "密码"; 1042
grant all privileges on TESTDB.* to 'testuser' @'localhost';
grant select,update on TESTDB.* to 'testuser' @'localhost';
#*.* 所有数据库; @"%"表示对所有非本地主机授权,不包括localhost。
grant select,delete,update,create,drop on *.* to testuser@"%" 
mysql> revoke  select on TESTDB.*  from testuser @'localhost';

#刷新授权
flush privileges;  

数据库

数据库的主体,类似电脑的分区或文件夹

mysql> create database TESTDB;
mysql> drop database TESTDB;
mysql> show databases;

#Python创建新的数据库
mydb.cmd_query("create database if not exists TESTDB")
mycursor.execute("create database if not exists TESTDB")

# 检查数据库是否存在
# mycursor.execute("SHOW DATABASES")
# for x in mycursor:
#     print(x)

mysql中把文件称为表,用于存储数据

# 创建表格
mycursor.execute("create table if not exists EMPLOYEE (ID INT AUTO_INCREMENT PRIMARY KEY, FIRST_NAME varchar(255), LAST_NAME varchar(255), AGE int, SEX int, INCOME int)")

SHOW TABLES
//insert
INSERT INTO sites (name, url) VALUES ('name','url')
//select
SELECT * FROM sites
SELECT name, url FROM sites
//where
SELECT * FROM sites WHERE name ='RUNOOB'
//使用通配符 %:
SELECT * FROM sites WHERE url LIKE '%oo%'
//排序 默认为升序
SELECT * FROM sites ORDER BY name
//降序排序
SELECT * FROM sites ORDER BY name DESC
//Limit
SELECT * FROM sites LIMIT 3
//指定起始位置,使用的关键字是 OFFSET:
SELECT * FROM sites LIMIT 3 OFFSET 1
//删除记录
DELETE FROM sites WHERE name = 'stackoverflow'
//更新表数据
UPDATE sites SET name = 'ZH' WHERE name = 'Zhihu'
//删除表
DROP TABLE IF EXISTS sites
# 主键 ADD COLUMN
mycursor.execute("ALTER TABLE sites ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY")

每一列存储对应的数据,比如姓名列,只存储用户的姓名,同一用户的数据应按照列存储到同一行,类似表格。

上一篇 下一篇

猜你喜欢

热点阅读