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
  • 相关阅读:
    操作系统(生产者、消费者问题)
    Hibernate——离线查询
    计算机网络(物理层习题)
    Mysql(笛卡尔积、等值连接、自然连接、外连接)
    vim文本编辑器——文件导入、命令查找、导入命令执行结果、自定义快捷键、ab命令、快捷键的保存
    vim文本编辑器——替换、保存退出
    CT107D电路解析
    vim文本编辑器——删除、复制、剪切、更改某一个字符、替换、撤销、关键字搜索
    文本编辑器vim——三种模式、显示行号、插入命令、行快速定位、行内定位
    关机、重启、退出登录命令
  • 原文地址:https://www.cnblogs.com/Forever77/p/10386482.html
Copyright © 2011-2022 走看看