• 10-Python操作MySQL


    python操作mysql

    pip install pymysql      

    要操作数据库,首先就要建立和数据库的连接,配置pymysql.connect连接数据库

    con = pymysql.connect(
        host = '主机',
        port = 端口,
        user = '用户名',
        password = '密码',
        db = '数据库名',
        charset = 'utf8'
    )
    # 定义游标
    cursor = con.cursor()  
    cursor.execute('show databases')        #执行sql
    one = cursor.fetchone()              #取出一条数据
    all = cursor.fetchall()              #取出所有数据
    print(one)
    print(all)
    # 插入 
    row = cursor.execute("insert into test(name,sex) values(%s,%s)", ('佳能','男'))
    #  更新
    row = cursor.execute("update test set name= '张三' where id = %s", (2,))
    #  删除
    cursor.execute('delete from user where id=%s ',(13,) )
    # 关闭连接
    con.commit()    #提交事物
    cursor.close()  #关闭游标
    con.close()     # 关闭连接
    ## 联合查询
    union = '''
    select  s.name, c.name,d.name  from  `student` s 
    left join `select` se on se.s_id = s.s_id
    left join course  c on se.c_id = c.id
    left join department d on s.dept_id = d.id
    ORDER BY s.name;
    '''
    # cursor.execute(union)
    # find =cursor.fetchall()
     

    python操作 redis

    pip  install redis
    # 创建连接
    re = redis.Redis(host='127.0.0.1', port='55555', password='qwe123')
    ## 测试
    re.set('num',15)
    print(re.get('num'))
    ## set 中文
    re.set('name','张三')
    print(re.get('name').decode('utf8') )
    ## 字符的 编码
    s = '佳能'.encode('utf8')
    print(type(s),s)
    s2 = s.decode()
    print(type(s2),s2)
    ### 大部分的命令 和 redis 中操作一样
    不同:
    re.ttl()       ### 不能看 负数 -1    -2
    re.mset()         ##  用键值对
    re.incr()        ## incr   可以加参数的,代替了 incrby
    re.decr()        ## decr   可以加参数,代替了 decrby
    re.lrem()        ## num 放到后面
    re.hmset()       # 多插入,要用字典
  • 相关阅读:
    Zabbix5 Frame 嵌套
    Zabbix5 对接 SAML 协议 SSO
    CentOS7 安装 Nexus
    CentOS7 安装 SonarQube
    GitLab 后台修改用户密码
    GitLab 查看版本号
    GitLab Admin Area 500 Error
    Linux 安装 PostgreSQL
    Liger ui grid 参数
    vue.js 是一个怪东西
  • 原文地址:https://www.cnblogs.com/Jack-Ma/p/8645654.html
Copyright © 2020-2023  润新知