Mysql回顾

举报
Buffoon 发表于 2021/10/07 10:05:56 2021/10/07
【摘要】 1、控制语句(1)连接数据库 mysql -uroot -p123456 -P3306 -h127.0.0.1; mysql -uroot -p123456 -P3306 -h127.0.0.1 -e"show databases"; //直接执行SQL语句(2)查看所有用户 select user, host from mysql.user;(3)新增用户 create user test...
1、控制语句
(1)连接数据库

mysql -uroot -p123456 -P3306 -h127.0.0.1;

mysql -uroot -p123456 -P3306 -h127.0.0.1 -e"show databases"; //直接执行SQL语句

(2)查看所有用户

select user, host from mysql.user;

(3)新增用户

create user test@'%' identified by 'password';

create user test@localhost identified by '123456';

(4)删除用户

drop user test@localhost;

(5)修改用户名

rename user test@localhost to te@loalhost;

(6)修改用户密码

update mysql.user set password = password('newpass') where user='test' and host = 'localhost';

(7)赋予权限

grant all privileges on *.* to 'test'@'localhost' identified by 'password';

flush privileges;

2、数据定义语句
库:
(1)创建数据库

create database if not exists test character set utf8;

(2)显示所有数据库

show databases;

(3)进入数据库

use test;

(4)删除数据库

drop database if exists test;

(5)修改数据库

alter database test character set utf8;

表:
(6)创建数据表

create table if not exists tb (

id char(10) not null primary key,

type varchar(20) not null default 'compute',

publicdata date not null,

num int(5),

price float(5)

) engine=InnoDB;

(7)显示当前库中所有数据表

show tables;

(8)修改数据表

alter table tb add column visit int(10) not null default 0, drop column publicdate;

(9)删除数据表

drop table if exists tb;

(10)显示表中字段信息

describe tb;

(11)清空表中记录

delete from tb;

3、数据更新语句
(1)插入数据

insert into tb (id, type, num, price, visit) values ('12346', 'math', 20, 30.5, 500);

(2)修改数据

update tb set type = 'compute', visit = 1000 where id = '12346'; //单表修改

update tb, sb set tb.visit = 4, sb.visit = 4 where tb.id = sb.id and tb.id = '123'; //多表修改

(3)删除数据

delete from tb where id = '12345';

4、数据查询语句
(1) 单表查询

select id as 编号, type as 类型 from tb where visit > 500 and type like 'c_m%' and num between 50 and 100 and price in (30.5, 30.2) and num is not null order by id desc limit 5;

select id, type,

case

when num is null then '卖光'

when num < 20 then '需进货'

when num >=20 and num < 100 then '正常'

when num >= 100 then '积压'

end as '库存'

from tb;

select type, sum(num) from tb group by type having sum(num) > 200;

(2)多表查询

select book.name, sell.num from book inner join sell on (book.id = sell.id);

select book.name, sell.num from book left outer join sell on (book.id = sell.id);

select book.name, sell.num from book right outer join sell on (book.id = sell.id);

select * from sell where id in (select id from book where visit > 100);

5、pymysql库简单使用
非类方式
#! /usr/bin/python3
import pymysql


def get_connection():
    conn = pymysql.connect(
        host="xx.xx.xx.xx",
        user="root",
        passwd="password",
        db="test",
        port=3306,
        charset="utf8",
    )
    csr = conn.cursor(cursor=pymysql.cursors.DictCursor)
    return conn, csr


def close_connection(conn, csr):
    if csr:
        csr.close()
    if conn:
        conn.close()


def query_sql(sql, params=None):
    result = None
    conn, csr = get_connection()
    try:
        csr.execute(sql, params)
        result = csr.fetchall()
    except Exception as e:
        print(str(e))
    finally:
        close_connection(conn, csr)
        return result


def update_sql(sql, params=None):
    result = None
    conn, csr = get_connection()
    try:
        result = csr.execute(sql, params)
        conn.commit()
    except Exception as e:
        conn.rollback()
        print(str(e))
    finally:
        close_connection(conn, csr)
        return result


if __name__ == "__main__":
    # ex_sql = "insert into tb (id, type, num, price, visit) values (%s, %s, %s, %s, %s )"
    # res = update_sql(ex_sql, ("12348", "english", 50, 38.5, 1200))
    # print(res)
    ex_sql = "select * from tb where visit > %s"
    res = query_sql(ex_sql, (500,))
    for r in res:
        print(r["id"], r["type"])

类方式
#! /usr/bin/python3
import pymysql
from dbutils.pooled_db import PooledDB


class DB(object):
    __pool = None
    def __init__(self):
        self.pool = DB.__get_conn_pool()
    @staticmethod
    def __get_conn_pool():
        if DB.__pool is None:
            DB.__pool = PooledDB(
                creator=pymysql,
                host="xx.xx.xx.xx",
                user="root",
                passwd="password",
                db="test",
                port=3306,
                charset="utf8",
                maxconnections=10240,
            )
        return DB.__pool
    def _get_connection(self):
        conn = self.pool.connection()
        csr = conn.cursor(cursor=pymysql.cursors.DictCursor)
        return conn, csr
    def _close_connection(self, conn, csr):
        if csr:
            csr.close()
        if conn:
            conn.close()
    def query_sql(self, sql, params=None):
        result = None
        conn, csr = self._get_connection()
        try:
            csr.execute(sql, params)
            result = csr.fetchall()
        except Exception as e:
            print(str(e))
        finally:
            self._close_connection(conn, csr)
            return result
    def update_sql(self, sql, params=None):
        result = None
        conn, csr = self._get_connection()
        try:
            result = csr.execute(sql, params)
            conn.commit()
        except Exception as e:
            conn.rollback()
            print(str(e))
        finally:
            self._close_connection(conn, csr)
            return result


if __name__ == "__main__":
    db = DB()
    # ex_sql = "insert into tb (id, type, num, price, visit) values (%s, %s, %s, %s, %s )"
    # res = db.update_sql(ex_sql, ("12348", "english", 50, 38.5, 1200))
    # print(res)
    ex_sql = "select * from tb where visit > %s"
    res = db.query_sql(ex_sql, (500,))
    for r in res:
        print(r['id'], r['type'])
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。