zoukankan      html  css  js  c++  java
  • 数据库-python操作mysql(pymsql)

    pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同

    一:安装pymysql

    pip3 install pymysql

    二:使用pytmysql

    # -*- coding:utf-8 -*-
    __author__ = 'shisanjun'
    
    import pymysql
    
    #创建连接
    conn=pymysql.connect(host="192.168.0.121",port=3306,user="admin",password="admin",db="test2")
    
    #创建游标
    cursor=conn.cursor()
    
    #执行sql,并还回影响的行数
    effct_row=cursor.execute("update student set name='shi' where name='shisanjun'")
    print(effct_row)
    
    #执行sql,并返回影响行数,多条记录执行
    effct_row=cursor.executemany("insert into student (name,age,sex) value (%s, %s, %s)",[("tianshi",23,"F"),("xiatian",24,"F")])
    
    conn.commit()
    
    #获取最新自增ID
    print(cursor.lastrowid)
    
    cursor.execute("select * from student")
    
    # 获取第一行数据
    print(cursor.fetchone())
    
    #获取前n行数据
    print(cursor.fetchmany(3))
    
    # 获取所有数据
    print(cursor.fetchall())
    
    conn.commit()
    cursor.close()
    conn.close()
    4
    9
    (1, 'shi', 23, 'M')
    ((2, 'shisanjun2', 23, 'M'), (4, 'shisanjun3', 24, 'F'), (5, 'shisanjun3', 25, 'F'))
    ((6, 'shi', 25, 'F'), (7, 'shi', 26, 'F'), (8, 'shi', 26, 'F'), (9, 'tianshi', 23, 'F'), (10, 'xiatian', 24, 'F'))

    注:在fetch数据时按照顺序进行,可以使用cursor.scroll(num,mode)来移动游标位置,如:

    • cursor.scroll(1,mode='relative')  # 相对当前位置移动
    • cursor.scroll(2,mode='absolute') # 相对绝对位置移动

    三:fetch数据类型

    关于默认获取的数据是元祖类型,如果想要或者字典类型的数据

    # -*- coding:utf-8 -*-
    __author__ = 'shisanjun'
    import pymysql
    
    #创建连接
    conn=pymysql.connect(host="192.168.0.121",port=3306,user="admin",password="admin",db="test2")
    
    #创建游标
    cursor=conn.cursor(cursor=pymysql.cursors.DictCursor)
    
    r=cursor.execute("select * from student")
    result=cursor.fetchall()
    print(r)
    print(result)
    
    conn.commit()
    cursor.close()
    conn.close()
    
    
    9
    [{'stu_id': 1, 'name': 'shi', 'age': 23, 'sex': 'M'}, {'stu_id': 2, 'name': 'shisanjun2', 'age': 23, 'sex': 'M'}, {'stu_id': 4, 'name': 'shisanjun3', 'age': 24, 'sex': 'F'}, {'stu_id': 5, 'name': 'shisanjun3', 'age': 25, 'sex': 'F'}, {'stu_id': 6, 'name': 'shi', 'age': 25, 'sex': 'F'}, {'stu_id': 7, 'name': 'shi', 'age': 26, 'sex': 'F'}, {'stu_id': 8, 'name': 'shi', 'age': 26, 'sex': 'F'}, {'stu_id': 9, 'name': 'tianshi', 'age': 23, 'sex': 'F'}, {'stu_id': 10, 'name': 'xiatian', 'age': 24, 'sex': 'F'}]
  • 相关阅读:
    pgspider 一些ppt 截图
    postgres cassandra_fdw 扩展试用
    使用 postgres s3 fdw + cube.js 分析 csv 数据
    cube.js 集成s3 的一种方法
    postgres s3 fdw 试用
    cube.js 集成 elasticsearch 的一种变通方法
    使用postgres_fdw 串接elasticsearch fdw
    postgres elasticsearch fdw 学习
    使用vcpkg 管理c&&c++ 包
    postgres pg_cron 扩展连接远程pg server
  • 原文地址:https://www.cnblogs.com/lixiang1013/p/7294730.html
Copyright © 2011-2022 走看看