• mysql python pymysql模块 增删改查 查询 字典游标显示


    我们看到取得结果是一个元祖,但是不知道是哪个字段的,如果字段多的时候,就比较麻烦

    '''
    (1, 'mike', '123')
    (2, 'jack', '456')
    '''


    用字典显示查询的结果,也可以查询到字段名

    在拿游标时候加上
    字典显示的游标
    cur = conn.cursor(pymysql.cursors.DictCursor)
    import pymysql
    
    
    
    mysql_host = '192.168.0.106'
    port = 3306
    mysql_user = 'root'
    mysql_pwd = '123'
    encoding = 'utf8'
    
    # 建立 连接mysql服务端
    
    conn = pymysql.connect(
        host=mysql_host,  # mysql服务端ip
        port=port,  # mysql端口
        user=mysql_user,  # mysql 账号
        password=mysql_pwd,  # mysql服务端密码
        db='db10',  # 操作的库
        charset=encoding  # 读取字符串编码
    
    )
    
    # 拿到游标对象
    cur = conn.cursor(pymysql.cursors.DictCursor)
    
    '''
    游标是给mysql提交命令的接口
    mysql> 
    把sql语句传递到这里
    '''
    
    
    # 执行sql语句
    # 增、删、改
    sql= 'select * from userinfo; '
    
    
    # 把sql语句传给游标执行
    # 让游标execute去帮我拼接字符串
    
    rows = cur.execute(sql)
    
    # 想看查询的内容 调游标对象
    # fetchone 取第一条记录
    print(cur.fetchone())
    print(cur.fetchone())
    print(cur.fetchone())
    print(cur.fetchone())
    print(cur.fetchone())
    print(cur.fetchone())
    
    
    # 执行完sql语句要关闭游标和mysql连接
    cur.close()
    conn.close()
    
    '''
    把字段也显示出来
    {'id': 1, 'name': 'mike', 'pwd': '123'}
    {'id': 2, 'name': 'jack', 'pwd': '456'}
    {'id': 3, 'name': 'alex', 'pwd': '555'}
    {'id': 4, 'name': 'peter', 'pwd': '989'}
    {'id': 5, 'name': 'app', 'pwd': '123'}
    {'id': 6, 'name': 'tom', 'pwd': '556'}
    '''
  • 相关阅读:
    ORACLE触发器具体解释
    秒杀多线程第四篇 一个经典的多线程同步问题
    Java中Integer类的方法
    九大排序算法再总结
    删除条目时的确认对话框
    VirtualBox安装及使用说明和虚拟机安装XP系统图文教程
    J2EE之验证码实现
    教你用笔记本破解无线路由器password
    vSphere HA状况:未知配置错误解决的方法
    HDU 2504 又见GCD
  • 原文地址:https://www.cnblogs.com/mingerlcm/p/9932542.html
Copyright © 2020-2023  润新知