zoukankan      html  css  js  c++  java
  • Pymysql

    1Pymysql

    在增删改文档的时候,必须要加上.commit确保修改的成功

    #pip3 install pymysql #安装pymysql模块,在python中可以使用于mysql之间交互
    
    import pymysql
    client=pymysql.connect(
        host='127.0.0.1',
        port=3306,
        user='root',
        password='yf123',
        database='db4',
        charset='utf8'
    )
    cursor=client.cursor()
    #mysql邮标是接受sql语句在cmd中,而python中是以cursor为邮标
    sql='insert into t1 values(2,"yf");'#sql语句
    try:
        res=cursor.execute(sql)#execute执行的意思
        print(res)
        client.commit() #改操作一定要commit
    except Exception:
        client.rollback()
    cursor.close()#关闭邮标
    client.close()#回收套接字资源

    2、增加,删除

    增加

    #pip3 install pymysql #安装pymysql模块,在python中可以使用于mysql之间交互
    import pymysql
    
    client=pymysql.connect(
        host='127.0.0.1',
        port=3306,
        user='root',
        password='yf123',
        database='db4',
        charset='utf8'
    )
    cursor=client.cursor()
    #mysql邮标是接受sql语句在cmd中,而python中 是以cursor为邮标
    userinfo=[
        (6,"cq"),
        (7,"zz"),
        (8,"hb")
    ]
    
    # for user in userinfo:
    sql='insert into t1 values(%s,%s);'#sql语句
    #
    #     res=cursor.execute(sql)#execute执行的意思
    cursor.executemany(sql,userinfo)#executemany就是循环出userinfo,不需要for循环
    client.commit() #改操作一定要commit
    cursor.close()#关闭邮标
    client.close()#回收套接字资源

    删除

    import pymysql
    
    client=pymysql.connect(
        host='127.0.0.1',
        port=3306,
        user='root',
        password='yf123',
        database='db4',
        charset='utf8'
    )
    cursor=client.cursor()
    cursor.execute('delete from t1 where id=3;')
    
    client.commit() #改操作一定要commit
    
    cursor.close()#关闭邮标
    client.close()#回收套接字资源

    3、调用存储过程

     

    在密码前输入password可以起到加密作用

     

     

     

    在密码输入之后会到数据库进行对比,如果有结果出来就代表输入的帐号密码是正确的

     

     

     

    每次删记录,针对默认递增的,如果下次注册信息不手动填补之前删除的id那么会造成跳空,直接按照最后一次的序列号继续下去,如果手动填补了之前的删除id,就算后面手动继续输入id存储,默认id递增序列也会自动跟从

     

     

     

    mysql--是同一行注释后面的内容

     

    Xxx” -- xxxxx

     

    Xxx” or 1=1 -- hellsb

     

    Mysql里面  没有密码或者帐号也能登入数据库,所以在前端以及后端都需要加防,特殊字符的取消

    import pymysql
    
    client=pymysql.connect(
        host='127.0.0.1',
        port=3306,
        user='root',
        password='yf123',
        database='db4',
        charset='utf8'
    )
    cursor=client.cursor(pymysql.cursors.DictCursor)
    #查询
    inp_user=input("输入账号名:").strip()
    inp_pwd=input("输入密码:").strip()
    
    sql='select id from user where name = "%s" and pwd = "%s";' %(inp_user,inp_pwd)
    rows = cursor.execute(sql)
    if rows:
        print("登入成功")
    else:
        print("用户名或者密码错误")
    
    
    cursor.close()#关闭邮标
    client.close()#回收套接字资源
    client=pymysql.connect(
        host='127.0.0.1',
        port=3306,
        user='root',
        password='yf123',
        database='db4',
        charset='utf8'
    )
    cursor=client.cursor(pymysql.cursors.DictCursor)#将fetchall拿到的结果以一个大列表的形式,
    # 里面的每一个消息内都是以字典的形式进行显示
    #查询
    inp_user=input("输入账号名:").strip()
    inp_pwd=input("输入密码:").strip()
    
    sql='select * from user where id > 3;'#执行sql语句不会在原地等,是异步过程
    rows = cursor.execute(sql,(inp_user,inp_pwd)) #这种方式,会在用户输入账号密码之后
    # 传输之前进行一个检查是否有特殊符号
    # print(rows)#是查询成功的行数
    #内存中拿结果
    
    
    # print(cursor.fetchall())#fetchall,查看所有的结果,以大元组的形式里面每一个结果以小元组方式
    # 用fetchall方式拿完一次,后面直接再拿就无法获取到
    # cursor.scroll(0,mode="absolute")#绝对位置移动,在第一次fetchall取完内容之后,再用scroll方式
    # absolute方法可以类似指针方式移动到最初位置,最前面的数字输入多少就是就是从最开始往后移动多少
    # print(cursor.fetchall())
    
    
    # print(cursor.fetchone())#每次拿一条信息
    # cursor.scroll(2,mode="relative")#相对当前位置移动,在目前所在位置向后移动,前面的数字代表
    # 移动的个数
    
    
    # print(cursor.fetchmany(2))#是从查询结果当中拿的条数,括号内填写的数字是针对一次拿几条的信息
    
    cursor.close()#关闭邮标
    client.close()#回收套接字资源
    提交查询语句并且拿到查询结果

    4、视图

    视图既是将虚拟表保存下来
    create view student2score as select * from student inner join score on student.sid = student_id;
    
    create view student2score as select student.*,score.sid as score_sid,student_id,course_id,num from student inner join score on student.sid = student_id;

    需要注意的是:

    创建视图需要create view student2score as

    另外如果表里面有重复字段会报错

    视图创建出来的表,只有表结构没有表内容,而表的内容都是通过查询语句每次查询出来的结果(另外两张表内),视图相当于就保存了sql语句,直接使用表不用每次连接表,不要去改视图里面的记录,主要是用查询,简化查询语句

    强调
    #1、字段名不能重复
    #2、视图是为了简化查询的sql语句,不应该修改视图中的记录
    删除视图
    drop view student2score视图名称

     

    5、触发器

    针对记录的增删改行为自动触发
    命名按照
    create trigger(创建触发器) (tri(触发器) _before(针对之前还是之后)_insert(针对什么行为)_tb1(哪张表))命名方式

    # 插入前CREATE TRIGGER tri_before_insert_tb1 BEFORE INSERT ON tb1 FOR EACH ROW
    BEGIN
        ...
    END
    # 插入后CREATE TRIGGER tri_after_insert_tb1 AFTER INSERT ON tb1 FOR EACH ROW
    BEGIN
        ...
    END
    # 删除前CREATE TRIGGER tri_before_delete_tb1 BEFORE DELETE ON tb1 FOR EACH ROW
    BEGIN
        ...
    END
    # 删除后CREATE TRIGGER tri_after_delete_tb1 AFTER DELETE ON tb1 FOR EACH ROW
    BEGIN
        ...
    END
    # 更新前CREATE TRIGGER tri_before_update_tb1 BEFORE UPDATE ON tb1 FOR EACH ROW
    BEGIN
        ...
    END
    # 更新后CREATE TRIGGER tri_after_update_tb1 AFTER UPDATE ON tb1 FOR EACH ROW
    BEGIN
        ...
    END
    CREATE TABLE cmd (
        id INT PRIMARY KEY auto_increment,
        USER CHAR (32),
        priv CHAR (10),
        cmd CHAR (64),
        sub_time datetime, #提交时间
        success enum ('yes', 'no') #0代表执行失败
    );
    
    CREATE TABLE errlog (
        id INT PRIMARY KEY auto_increment,
        err_id int,
    );
    delimiter $$ #更改结束符号
    CREATE TRIGGER tri_after_insert_cmd AFTER INSERT ON cmd FOR EACH ROW
    BEGIN
        if NEW.success = 'no' then
            insert into errlog(err_id) values(NEW.id);
        end if;
    END $$
    delimiter ;

    6、事务

     

    transaction 事务,交易
    事务可以包含一系列的sql语句,事务的执行具有原子性
    1、原子性:
    包含多条sql语句,要么都执行成功,要么都执行不成功
    2、回滚
    rollback,遇到情况就回滚到之前状态,就像什么都没发生过一样
    start transaction;开启事务
    在这里面做的所有修改如果遇到rollback就会回到原来的状态

    start transaction;
    try:
        update user set balance=900 where id=1;
        update user set balance=1010 where id=2;
        update user set balance=1090 where id=3;
        commit;
    except Exception:
        rollback;

    7、流程控制:

    delimiter //
    create procedure proc_while()
    begin
        declare num int;
        set num = 0;
        while num < 10 do
            select
                num;
            set num = num+1;
        end while;
    end //
    delimiter;
    while循环
    delimiter //
    create procedure proc_repat()
    begin
        declare i int;
        set i = 0;
        repeat
            select i;
            set i=i+1;
            until i>=5
        end repeat;
    end//
    delimiter;
    repeat循环
    begin
        declare i int default 0;
        loop_label:loop
            set i=i+1;
            if i<8 then
                iterate loop_label;
            end if;
            if i>=10 then
                leave loop_label;
            end if;
            select i;
        end loop loop_label
    end
    loop循环

    8、函数

     

    select date_format(sub_time,"%Y-%m"),count(id) from blog group by date_format(sub_time,"%Y-%m");#不要单独使用,要在sql语句中使用

     

    9、存储过程

    delimiter $$
    create procedure p1() #建到某一个库下,p1存储过程名
    begin
           select * from blog;
    end $$
    delimiter ;
    
    call p1()#用call进行调用存储过程,存储过程是一系列sql语句的结合体,里面可以用mysql里面的所有功能,
    是mysql一堆功能的封装体,给应用程序用
    
    
    create table s1(
    id int,
    name varchar(20),
    gender char(6),
    email varchar(50)
    );#将表存放进
    
    delimiter $$  #定义阶段
    create procedure p2()
    BEGIN
        declare n int default 1;
        while (n < 100000) do
            insert into s1 values(n,concat('yf',n),'male',concat('yf',n,'@163.com'));
            set n=n+1;
        end while;
    END $$
    delimiter ;
    无参
    delimiter $$
    create procedure p3(
        in n int,
        out res int      #进行返回
        inout x int       #既能传值也能获得返回值,用其中一个就行
    )
    begin
           select * from blog where id>3;
           set res = 0; #返回值
    end $$
    delimiter ;
    
    针对out参数要传变量
    set @x=111;
    call p3(3,@x) #然后再调用 返回值为0就成功了
    select @x;
    +------+
    | @x   |
    +------+
    |    0 |
    +------+
    
    在python中调用:
    cursor.callproc('p4',(3,111)) #set @_p4_0 = 3; set @_p4_1 = 111
    print(cursor.fetchall())
    cursor.execute('select @_p4_1;')
    print(cursor.fetchone())
    有参

     

  • 相关阅读:
    走进MongoDB(二)
    走进MongoDB(一)
    InnoDB锁与事务模型
    InnoDB引擎架构的主要组件构成
    InnoDB多版本存储引擎简介
    mysql 数据库备份与恢复
    mysql 字符集
    java常见问题笔记
    mysql5.7 Installing MySQL on Microsoft Windows Using a noinstall Zip Archive(mysql解压版安装)
    作业day03吴童
  • 原文地址:https://www.cnblogs.com/yf18767106368/p/9367928.html
Copyright © 2011-2022 走看看