zoukankan      html  css  js  c++  java
  • python操作pymysql数据库

    首先需要导入通过import pymysql导入数据库模块

    已经创建好一个数据库test,数据库中有一个空表t,只有两个字段id int(5),name varchar(20)

    import pymysql
    
    conn=pymysql.connect(host='127.0.0.1',port=3306,user='root',password='oldboy',db='test')  #创建与数据库的连接对象,需要指明数据库所在主机ip、端口、登录用户名、登录密码、使用数据库
    cursor=conn.cursor()   #创建与数据库的交互对象
    sql1="insert into t values (1,'Jack'), (2,'Bob'), (3,'Alice'),(4,'Jane')"
    cursor.execute(sql1) #通过交互对象执行sql语句
    
    conn.commit()  #通过连接对象提交修改
    cursor.close()   #关闭交互对象
    conn.close()  #关闭连接对象

    以上,conn=句为创建与数据库的连接对象,cursor=句为创建与数据库的交互对象

    conn.commit()为提交修改即将修改记录到数据库中,cursor.close()和conn.close()为关闭交互对象和连接对象。

    sql2="select * from t"
    cursor.execute(sql2) 
    print(cursor.execute(sql2))  #结果为执行sql2语句影响的记录数
    print(cursor.fetchone())  #取execute(sql2)执行结果的第一条记录
    #print(cursor.fetchmany(2))  取执行结果的前2条记录
    #print(cursor.fetchall())  取执行结果的所有记录

    通过cursor.execute执行查询语句后,查询结果会放置到cursor中,可通过fetchone()、fetchmany()和fetchall()从cursor获取值,在取值的过程中,游标会自动地向后移动。

    手动移动游标的位置,通过cursor.scroll(n,mode=[relative|absolute])实现。

    sql2="select * from t"
    cursor.execute(sql2)
    print(cursor.fetchmany(2))   #((1, 'Jack'), (2, 'Bob'))
    cursor.scroll(-1,mode='relative')
    print(cursor.fetchone())   #(2, 'Bob')
    cursor.scroll(3,mode='absolute')
    print(cursor.fetchone())   #(4, 'Jane')

    相对位置移动游标位置:cursor.scroll(-1,mode='relative'),使用mode='relative',前面的数据参数如果为负表示相对当前位置向前移动指定数量的游标,为正则表示相对当前位置向后移动指定数量的游标。

    绝对位置移动游标位置:cursor.scroll(3,mode='absolute'),使用mode='absolute',前面的数据参数是正数,表示移动到的位置,0表示第一个,最大值为结果的长度-1,超出会报IndexError: out of range错误。

    sql2="select * from t"
    cursor.execute(sql2)
    cursor.scroll(4,mode='absolute')
    print(cursor.fetchone())  
    
    #    raise IndexError("out of range")
    #IndexError: out of range
  • 相关阅读:
    .NetCore Grpc 客服端 工厂模式配置授权
    DOCKER 拉取 dotnet 镜像太慢 docker pull mcr.microsoft.com too slow
    Introducing .NET 5
    VSCode 出现错误 System.IO.IOException: The configured user limit (128) on the number of inotify instances has been reached.
    Omnisharp VsCode Attaching to remote processes
    zookeeper3.5.5 centos7 完全分布式 搭建随记
    Hadoop2.7.7 centos7 完全分布式 配置与问题随记
    MySQL索引 索引分类 最左前缀原则 覆盖索引 索引下推 联合索引顺序
    SQL基础随记3 范式 键
    MySQL调优 优化需要考虑哪些方面
  • 原文地址:https://www.cnblogs.com/Forever77/p/10386482.html
Copyright © 2011-2022 走看看