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

 

posted @ 2019-02-15 23:38  Forever77  阅读(629)  评论(0编辑  收藏  举报