pymysql

什么是pymysql?

  它是你的python和数据库交互的模块 ,你的python的几乎所有的和mysql数据库交互的底层都是基于mysql来做的

使用mysql首先你要导入pymysql模块

import pymysql

我们要先创建连接  然后再创建游标 用游标去进行你的信息的插入 操作

# 连接
conn = pymysql.connect(host='localhost', user='root', password='', database='db2', port=3306)

# 创建游标
cursor = conn.cursor()

sql = "select * from userinfo where username = '%s' and pwd = '%s'"%(username,pwd)

print(sql)

# 受影响的行数
r = cursor.execute(sql)

print(r)

# 关闭
cursor.close()
conn.close()

connect是创建连接

cursor是创建游标

execute是进行你的sql语句的操作插入

execute是对一行进行操作  而想要对多行操作需要用executemany

r = cursor.executemany(sql,[('张三','110'),('dadad','119')])

当你操作完毕后一定要把你的信息提交

# 一定要commit
conn.commit()

# 关闭
cursor.close()
conn.close()

execute是操作你的插入 修改删除的  

 

查询:fetch都是用创建的游标来操作

查询单行:

row = cursor.fetchone()

查询多行:fetchmany()

rows = cursor.fetchmany(3)

查询所有fetchall

rows = cursor.fetchall()

然后操作完成再把连接给关闭

 连接
conn = pymysql.connect(host='localhost', user='root', password='', database='db2', port=3306,charset='utf8')

# 创建游标
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)


sql = 'select * from userinfo'
effect_row = cursor.execute(sql)



# rows = cursor.fetchmany(3)


# rows = cursor.fetchall()
# print(rows)

row = cursor.fetchone()
print(row)

row = cursor.fetchone()
print(row)


row = cursor.fetchone()
print(row)

cursor.scroll(5,mode='absolute')

row = cursor.fetchone()
print(row)



# 关闭
cursor.close()
conn.close()
原文地址:https://www.cnblogs.com/zhaoyunlong/p/9615075.html