PyMySQL的基本操作

什么是 PyMySQL?

PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb。

PyMySQL 遵循 Python 数据库 API v2.0 规范,并包含了 pure-Python MySQL 客户端库。

PyMySQL的安装

pip3 install pymysql
#pymysql模块,同属于套接字模块。

PyMySQL的基本使用

使用PyMySQL模块固定不变的执行顺序

  1. 建立连接
  2. 拿到游标
  3. 执行SQL语句
  4. 关闭(游标、连接)

小例子:

import pymysql

username = input('>>>:').strip()
pwd = input('>->>:').strip()

#建立连接
db = pymysql.connect(
     host='192.168.9.99',
     port=3306,
     user='root',
     password='123',
     db = 'dbname',
     charset='utf8',
     )

#拿到游标
cursor = db.cursor()

#执行SQL语句
# sql = 'select * from userinfo where username = "%s" and pwd = "%s"'
sql = 'insert into userinfo(username,pwd) values (%s,%s)'

try:
   #rows变量得到数据库中被影响的数据行数。
   rows = cursor.execute(sql, (username, pwd))

   # 向数据库提交
   db.commit()
   #如果没有commit(),库中字段已经向下移位但内容没有写进,可是自动生成的ID会自动增加。
except:
   # 发生错误时回滚
   db.rollback()

#关闭(游标、数据库)
cursor.close()
db.close()

if rows: #通过ROWS的返回值来判断执行结果。
    print('连接成功')
else:
    print('登录失败')

插入多条数据:executemany()

使用executemany()来多条插入信息。要用列表包含元组的形式插入。[(),(),()]

例如:rows = cursor.executemany(sql,[('sly','123),('hh','123')])
#这个例子中的rows可以不加。它的作用是记录影响的行数。

查询

取返回数据用 fetch(一共三种)

  1. fetchone() 一次一条数据。
  2. fetchmany() 一次多条数据,括号内填入要读取的数据条数。不填则为1条数据,如果读数超过实际条数,只显示实际条数。
  3. fetchall() 一次读取全部数据,如果管道内没有数据,则返回空元组或空列表。

    例如:printcursor.fetchone()) 在管道中取一条数据。
    注意:用fetchone()取值超过最大数会返回None

将取回值以字典形式显示:pymysql.cursors.DictCursor

需在拿游标时加载

例如:cursor = db.cursor(pymysql.cursors.DictCursor)

移动指针

注意:当一次查询结束后,再次查询时为空,是因为指针到了最后位,如果想再次查找就需要将指针指向指定的位置。另外,指针的位置与列表一样,首位为0。(第0位为第一条数据)

指针的移动有两种:

1,相对绝对位置移动:absolute

#指的是由第一条记录开始的第N个位置
#例如:
scroll(2,mode='absolute') #指针指向数据的第2位这条记录。数据的第一条记录为第0位。

2,相对当前位置移动: relative

#指的是由当前的记录位置开始的第N个位置
#例如:
scroll(3,mode='relative') #指针指向当前数据位置的后数3位的记录。

3,查询当前数据库中指针位置:lastrowid

#上次光标位置
print(cursor.lastrowid)

小练习:

import pymysql

conn = pymysql.connect(
    host='127.0.0.1',
    port=3306,
    user='sly',
    password='123',
    db='pytest'
)

cursor = conn.cursor(pymysql.cursors.DictCursor)

sql = 'select * from userinfo'
# sql = 'select * from userinfo where user=%s and pwd=%s' #查询
# sql = 'select * from userinfo where user="%s" and pwd="%s"' % (user, pwd) #该方法不安全,要使用PYMYSQL模表导入。
# sql = 'insert into userinfo (user,pwd) value (%s,%s)'  #增加
# sql = 'update userinfo set user=%s where user=%s'  #更改
# sql = 'delete from userinfo where user=%s and pwd=%s' #删除

# print(sql)
# rows = cursor.execute(sql, (user, pwd))
# rows = cursor.executemany(sql, [('sly1', '123'), ('sly2', '123'), ('sly3', '123')])
rows = cursor.execute(sql)
print(cursor.lastrowid)

cursor.scroll(1, mode='absolute')
print(cursor.fetchone())
# cursor.scroll(2, mode='relative')
print('this is fetch one...')
print(cursor.fetchmany(2))
print('this is fetch many....')
print(cursor.fetchall())
print('this is fetch all...')
print(rows)

conn.commit()

cursor.close()
conn.close()
原文地址:https://www.cnblogs.com/sly27/p/9141048.html