安装
sudo pip3 install pymysql
说明
查看安装包的信息
pip3 show 包名
查看安装的第三方包的列表
pip3 list
使用
代码示例-查
if __name__ == '__main__':
# 1.导包
import pymysql
# 2.创建连接对象
conn = pymysql.connect(host="x.x.x.x",
port=3306,
user="root",
password="123456",
database="python",
charset="utf8")
# 3.获取游标,目的就是执行sql语句
cursor = conn.cursor()
# 准备sql
sql = "select * from students;" # 查
# 4、执行sql语句
cursor.execute(sql)
# 获取查询的结果,返回的数据类型是一个元祖
# row = cursor.fetchone()
# print(row)
# 获取结果所有数据
result = cursor.fetchall()
for row in result:
print(row)
# 5.关闭游标
cursor.close()
# 6.关闭连接
conn.close()
代码示例-增删改
if __name__ == '__main__':
# 1.导包
import pymysql
# 2.创建连接对象
conn = pymysql.connect(host="x.x.x.x",
port=3306,
user="root",
password="123456",
database="python",
charset="utf8")
# 3.获取游标,目的就是执行sql语句
cursor = conn.cursor()
# 准备sql
# sql = "select * from students;" # 查
sql = "insert into classes(name) values('java');" # 增
sql = "update classes set name = 'html' where id = 4;" # 改
sql = "delete from classes where id = 4;" # 删
try:
# 4、执行sql语句
cursor.execute(sql)
# 提交修改的数据到数据库
conn.commit()
except Exception as e:
conn.rollback()
# 获取查询的结果,返回的数据类型是一个元祖
# row = cursor.fetchone()
# print(row)
# 获取结果所有数据
# result = cursor.fetchall()
# for row in result:
# print(row)
# 5.关闭游标
finally:
cursor.close()
# 6.关闭连接
conn.close()