如果你对该文章中的内容有疑问/不解,可以点击此处链接提问
要注明问题和此文章链接地址 点击此处跳转
安装
安装 pip3 install pymysql
python3 import pymysql
python2 import MySQLdb
操作sql
增
<code class="">import pymysql
conn = pymysql.connect(
host='192.168.0.103',
port=3306,
user='root',
password='123',
database='xing',
charset='utf8'
)
cursor = conn.cursor() # 获取一个光标
sql = 'insert into userinfo (user,pwd) values (%s,%s);'
name = 'wuli'
pwd = '123456789'
cursor.execute(sql, [name, pwd])
conn.commit()
last_id = cursor.lastrowid
print("最后一条数据的ID是:", last_id)
cursor.close()
conn.close()
</code>
删
<code class="">import pymysql
# 建立连接
conn = pymysql.connect(
host="192.168.0.103",
port=3306,
user="root",
password="123",
database="xing",
charset="utf8"
)
# 获取一个光标
cursor = conn.cursor()
# 定义将要执行的SQL语句
sql = "delete from userinfo where user=%s;"
name = "june"
# 拼接并执行SQL语句
cursor.execute(sql, [name])
# 涉及写操作注意要提交
conn.commit()
# 关闭连接
cursor.close()
conn.close()
</code>
改
<code class="">import pymysql
# 建立连接
conn = pymysql.connect(
host="192.168.0.103",
port=3306,
user="root",
password="123",
database="xing",
charset="utf8"
)
# 获取一个光标
cursor = conn.cursor()
# 定义将要执行的SQL语句
sql = "update userinfo set pwd=%s where user=%s;"
# 拼接并执行SQL语句
cursor.execute(sql, ["july", "july"])
# 涉及写操作注意要提交
conn.commit()
# 关闭连接
cursor.close()
conn.close()
</code>
查
<code class="">import pymysql
conn = pymysql.connect(
host='192.168.0.103',
port=3306,
user='root',
password='123',
database='xing',
charset='utf8'
)
# 获取一个光标
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 返回字典数据类型
# 定义将要执行的sql语句
sql = 'select user,pwd from userinfo;'
# 拼接并执行sql语句
cursor.execute(sql)
# 取到查询结果
ret1 = cursor.fetchone() # 取一条
ret2 = cursor.fetchmany(3) # 取三条
ret3 = cursor.fetchone() # 取一条
cursor.close()
conn.close()
print(ret1)
print(ret2)
print(ret3)
# 可以获取指定数量的数据
cursor.fetchmany(3)
# 光标按绝对位置移动1
cursor.scroll(1, mode="absolute")
# 光标按照相对位置(当前位置)移动1
cursor.scroll(1, mode="relative")
</code>