1.查询数据
八个步骤: 1.导包:import pymysql
2.连接mysql数据库服务:conne = pymysql.Connect()
3.创建游标对象:cur = conne.cursor()
4.编写sql语句:sql = 'select * from 万能表;'
5.使用游标对象调用sql语句:cur.execute(sql)
6.获取查询结果集,返回的是列表:result = cur.fetchall()
7.关闭游标对象:cur.close()
8.关闭连接:conne.close()
例子:
# 使用步骤
# 1.导包
import pymysql
# 2.连接mysql数据库服务
try:
conne = pymysql.Connect(
user='root',
password='Z20020803',
# host='192.168.68.130',
host = 'localhost',
database='itcast',
port=3306,
charset='utf8'
)
# 3.创建游标对象
cor = conne.cursor()
# 4.编写SQL语句
sql = 'select * from 万能表;'
# 5.使用游标对象调用SQL语句
cor.execute(sql)
# 6.获取查询结果集,返回的是列表
result = cor.fetchall()
print(result)
# 7.关闭游标对象
cor.close()
# 8.关闭连接
conne.close()
except Exception as e:
print(e)
2. 增加、修改和删除数据
步骤和查询一样,但是要增加一个提交操作:conne.commit()
例子:
try:
# 1.导包
import pymysql
# 2.连接mysql数据库服务
conne = pymysql.Connect(
user = 'root',
host = 'localhost',
port = 3306,
password = 'Z20020803',
database = 'itcast',
charset = 'utf8'
)
# 3.创建游标对象
cur = conne.cursor()
# 4.编写sql语句
# 增加数据
# 方式一
insert_sql = "insert into 万能表 (姓名, 性别, 年龄) values ('lly', '女', 20);"
# 方式二
insert_sql2 = "insert into 万能表 (姓名, 性别, 年龄) values (%s, %s, %s);"
# 删除数据
delete_sql = "delete from 万能表 where 姓名 is null;"
# 更改数据
update_del = "update 万能表 set 性别 = '女' where 姓名 = '张三';"
# 5.用游标对象调用sql语句
# cur.execute(insert_sql) # 增加数据语句调用
cur.execute(insert_sql2, ['曾浩', '男', 20]) # 待用增加函数,传递的参数必须是列表
# cur.execute(delete_sql) # 删除数据语句调用
# cur.execute(update_del) # 更改数据
# 6.提交数据,只有提交,数据库才会记录数据
conne.commit()
except Exception as e:
print(e)
# 数据回滚
conne.rollback()
# 7.关闭游标对象
cur.close()
# 8.关闭连接服务
cur.close()