Mysqlpythonpandas

MySQL札记18——游标cursor

2019-08-19  本文已影响0人  皮皮大

游标基础知识

SQL检索操作返回一组称为结果集的行。但是有时候,我们需要在检索出来的行中,需要前进或者后退一行甚至多行,这个时候需要使用游标cursor

游标是一个存在DBMS服务器上的数据库查询,它不仅是一条SELECT语句,而是被该语句检索出来的结果集。在存储了游标之后,应用程序可以根据需要滚动或者浏览其中的数据。不同的DBMS支持不同的游标选项和特性:

使用游标

使用步骤

创建游标

使用DECLARE语句来创建、定义和命名游标

declare Custcursor cursor for     # Custcursor 是游标的名字
select * from customers 
where cust_email is null;

使用游标

使用即打开游标的关键词是open,在处理open语句的时候,执行查询操作,存储检索出的数据以供浏览和滚动

open cursor Custcursor    # Custcursor 是游标的名字

关闭游标

关闭游标的关键词是close。游标一旦关闭,如果不再次打开,将无法使用;第二次使用的时候,不需要声明,直接open即可

close Custcursor   # 关闭游标

Python中操作MySQL

连接数据库

使用的是pymysql模块,需要先进行导入

使用模块的connect()进行连接

import pymysql
conn = pymysql.connect(host=“localhost”, port=3306, user="root", passwd="123456", db="bookdb", charset="utf8")

操作数据库

Python建立了和数据库的连接,实际上就是建立了一个pymysql.connect()实例对象,或者称之为连接对象Python就是通过连接对象和数据库进行对话。pymysql.connect()实例对象的方法有:

游标对象cur的操作方法

名称 描述
close 关闭游标
execute 执行一条SQL语句,可以带上参数;
执行之后需要conn.commit(),数据库中才会真正建立
fetchone 返回一条语句
fetchall 返回所有的语句
fetchmany 返回many条语句
nextset() 移动到下一个结果
import pymysql    # 导入模块
conn = pymysql.connect(host=“localhost”, port=3306, user="root", passwd="123456", db="bookdb", charset="utf8")      # 建立python和数据库的连接
cur = conn.cursor()  # 建立游标对象
cur.execute("insert into users (username, passwd, email) values (%s,  %s, %s)", ("python", "123456", "python@gmail.com"))   # 需要再执行conn.commit()

cur.executemany("insert into users (username, passwd, email) values (%s,  %s, %s)", (("python", "123456", "python@gmail.com"), ("java", "456789", "java@gmail.com"), ("php", "123789", "php@gmail.com")))
>>cur.execute("select * from users")
>>lines = cur.fetchall()   # 返回所有的查询结果
>>for line in lines:
    print(line)

# 只想返回一条结果
>>cur.execute("select * from users where id=1")  # 查询id=1

>>cur.execute("select * from users")
>>cur.fetchone()   # 返回一条结果;游标会跟着移动,直到将所有的数据取完
>>cur.fetchone() 
>>cur.fetchone() 
>>cur.scroll(2)  # 相对于当前位置移动
>>cur.fetchone()  # 显示数据
>>cur.scroll(2, "absolute")   # 加上参数,实现“绝对移动”,到第三条

绝对移动的数字不能是负数,相对移动可以是负数

Python的连接对象的游标方法中提供一个参数,将读取到的数据保存成字典形式:

>>cur = conn.cursor(pymysql.cursors.DictCursor)
>>cur.execute("select * from users")
>>cur.fetchall()

更新

>>cur.execute("update users set username=s% where id=2", ("mypython"))   # 更新第二条语句
>>cur.execute("select * from users where id=2")
>>cur.fetchone()
上一篇下一篇

猜你喜欢

热点阅读