pip install pymysql
# 导入模块
import pymysql
# 创建连接对象
conn = pymysql.connect(
# 用户名
user='root',
# 密码
password='000',
# 服务器地址,本地填写localhost或者127.0.0.1
host='localhost',
# 端口号,mysql默认是3306
port=3306,
# 连接的数据库,如果不指定将在最外层
database='pymysql_test',
# 返回的结果集将以字典的形式进行存储
cursorclass=pymysql.cursors.DictCursor,
)
# 创建游标
cursor = conn.cursor()
# 关闭游标和连接
cursor.close()
conn.close()
# sql语句
create_table_sql = '''
create table if not exists employee(
id int primary key auto_increment,
name varchar(10) not null,
sex enum('female', 'male') default 'female',
age int);
'''
# 执行mysql语句
cursor.execute(create_table_sql)
%s
来表示参数的位置。转换说明符 | 解释 |
---|---|
%d、%i | 转换为带符号的十进制数 |
%o | 转换为带符号的八进制数 |
%x、%X | 转换为带符号的十六进制数 |
%e | 转化为科学计数法表示的浮点数(e 小写) |
%E | 转化为科学计数法表示的浮点数(E 小写) |
%f、%F | 转化为十进制浮点数 |
%g | 智能选择使用 %f 或 %e 格式 |
%G | 智能选择使用 %F 或 %E 格式 |
%c | 格式化字符及其ASCII码 |
%r | 使用 repr() 函数将表达式转换为字符串 |
%s | 使用 str() 函数将表达式转换为字符串 |
# sql语句
tuple_insert = """
insert employee(name, sex, age)
values(%s, %s, %s)"""
# 执行sql语句
cursor.execute(tuple_insert, ('bruce', 'male', 18))
# 提交事务
conn.commit()
# sql语句
list_insert = """
insert employee(name, sex, age)
values(%s, %s, %s);"""
# 执行sql语句
cursor.execute(list_insert, ['lily', 'female', 28])
# 提交事务
conn.commit()
# sql语句
dict_insert = """
insert employee(name, sex, age)
values(%(name)s, %(sex)s, %(age)s);"""
# 执行sql语句
cursor.execute(dict_insert, {"name": 'tom', "age": 32, "sex": 'male'})
# 提交事务
conn.commit()
# sql语句
more_insert = """
insert employee(name, sex, age)
values(%s, %s, %s);"""
# 数据列表, 具体数据用元组包裹
data_list = [('lala', 'female', 22),
('lulu', 'male', 25),
('kan', 'male', 22),
('liuliu', 'female', 26)]
# 执行sql语句
cursor.executemany(more_insert, data_list)
# 提交事务
conn.commit()
commit
来提交事务。fetchall
# sql语句
search_all = "select * from employee;"
# 执行SQL语句
cursor.execute(search_all)
# 拿到返回结果
res = cursor.fetchall()
# 打印结果
print(res)
[{'id': 1, 'name': 'bruce', 'sex': 'male', 'age': 18}, {'id': 2, 'name': 'lily', 'sex': 'female', 'age': 28}, {'id': 3, 'name': 'tom', 'sex': 'male', 'age': 32}, {'id': 4, 'name': 'lala', 'sex': 'female', 'age': 22}, {'id': 5, 'name': 'lulu', 'sex': 'male', 'age': 25}, {'id': 6, 'name': 'kan', 'sex': 'male', 'age': 22}, {'id': 7, 'name': 'liuliu', 'sex': 'female', 'age': 26}]
fetchone
执行sql语句时
返回字典格式
# sql语句
search_one = "select * from employee;"
# 执行sql语句
row = cursor.execute(search_one)
print(f"总共有{row}条数据")
# 循环获取结果并打印
for i in range(row):
print(cursor.fetchone())
总共有7条数据
{'id': 1, 'name': 'bruce', 'sex': 'male', 'age': 18}
{'id': 2, 'name': 'lily', 'sex': 'female', 'age': 28}
{'id': 3, 'name': 'tom', 'sex': 'male', 'age': 32}
{'id': 4, 'name': 'lala', 'sex': 'female', 'age': 22}
{'id': 5, 'name': 'lulu', 'sex': 'male', 'age': 25}
{'id': 6, 'name': 'kan', 'sex': 'male', 'age': 22}
{'id': 7, 'name': 'liuliu', 'sex': 'female', 'age': 26}
fetchmany
# sql语句
search_many = "select * from employee;"
# 执行sql语句
get_row = cursor.execute(search_many)
# 循环打印,每次获取两条结果
for i in range((get_row + 1) // 2):
print(cursor.fetchmany(2))
[{'id': 1, 'name': 'bruce', 'sex': 'male', 'age': 18}, {'id': 2, 'name': 'lily', 'sex': 'female', 'age': 28}]
[{'id': 3, 'name': 'tom', 'sex': 'male', 'age': 32}, {'id': 4, 'name': 'lala', 'sex': 'female', 'age': 22}]
[{'id': 5, 'name': 'lulu', 'sex': 'male', 'age': 25}, {'id': 6, 'name': 'kan', 'sex': 'male', 'age': 22}]
[{'id': 7, 'name': 'liuliu', 'sex': 'female', 'age': 26}]
scroll
语法操作
数据库的结果集通常是单向的,即从头到尾的顺序读取
# 相对于起始位置位置往后移动
cursor.scroll(1, 'absolute')
# 相对当前位置往后移动
cursor.scroll(1, 'relative')
移动范围
返回的结果可以看成是一个管道
光标就是正要输出的数据的下表
使用fetchone
和scoll
实现打印偶数编号员工
# sql语句
search_scroll = 'select * from employee;'
# 执行sql语句
row_sum = cursor.execute(search_scroll)
# 超出范围会报错
# cursor.scroll(row_sum+1)
# 使用光标移动打印出编号为偶数的员工信息
i = 1
while i < row_sum:
cursor.scroll(1, 'relative')
print(cursor.fetchone())
i += 2
{'id': 2, 'name': 'lily', 'sex': 'female', 'age': 28}
{'id': 4, 'name': 'lala', 'sex': 'female', 'age': 22}
{'id': 6, 'name': 'kan', 'sex': 'male', 'age': 22}
# 修改前的信息
search_sql1 = """
select * from employee
where char_length(name) = 4;"""
cursor.execute(search_sql1)
print("修改前的信息:")
print(cursor.fetchall())
修改前的信息:
[{'id': 2, 'name': 'lily', 'sex': 'female', 'age': 28}, {'id': 4, 'name': 'lala', 'sex': 'female', 'age': 22}, {'id': 5, 'name': 'lulu', 'sex': 'male', 'age': 25}]
# sql语句
update_sql = """
update employee
set age = %s
where name regexp '....';"""
# 执行sql语句
cursor.execute(update_sql, 18)
# 提交修改事务
conn.commit()
search_sql2 = """
select * from employee
where name like '____';"""
cursor.execute(search_sql2)
print("修改后的信息:")
print(cursor.fetchall())
修改后的信息:
[{'id': 2, 'name': 'lily', 'sex': 'female', 'age': 18}, {'id': 4, 'name': 'lala', 'sex': 'female', 'age': 18}, {'id': 5, 'name': 'lulu', 'sex': 'male', 'age': 18}]
# 查询sql
search_sql = """
select *
from employee
where age > %s;"""
cursor.execute(search_sql, 22)
print(f"要删除的员工信息:")
print(cursor.fetchall())
要删除的员工信息:
[{'id': 3, 'name': 'tom', 'sex': 'male', 'age': 32}]
# 删除sql
delete_sql = """
delete from employee
where age > %s;"""
# 执行sql语句
cursor.execute(delete_sql, 22)
# 提交事务
conn.commit()
login_sql = "select * from u_p where username='%s' and password = '%s'" % (username, password)
# 导入模块
import pymysql
# 创建连接
conn = pymysql.connect(
user='root',
password='000',
host='localhost',
port=3306,
cursorclass=pymysql.cursors.DictCursor
)
cursor = conn.cursor()
# 创建user_info库
cursor.execute('create database if not exists user_info;')
conn.commit()
# 切换到数据库
cursor.execute('use user_info;')
conn.commit()
# 创建用户密码表
cursor.execute('create table if not exists u_p(username varchar(20) unique, password varchar(10));')
conn.commit()
# 获取用户名和密码
def get_username_password():
while True:
username = input("用户名:>>>").strip()
password = input("密码:>>>").strip()
# 检查长度是否符合要求
if (0 < len(username) < 20) and (0 < len(password) < 20): break
print("用户名或密码不能为空也不能超过20个字符")
continue
return username, password
# 注册
def register():
# 获取用户名和密码
username, password = get_username_password()
# 查看是否已经注册
get_info_sql = 'select * from u_p;'
num = cursor.execute(get_info_sql)
tag = False
for i in range(num):
if username == cursor.fetchone()["username"]:
tag = True
break
if tag: return f"{username} 已经注册,请更换用户名或者登录"
# 填写注册信息
register_sql = "insert u_p values(%s, %s);"
cursor.execute(register_sql, (username, password))
conn.commit()
return f"{username} 注册成功"
# 登录
def login():
# 先判断是否有人注册
row = cursor.execute('select * from u_p;')
if not row: return "当前还没有用户注册,请先注册"
# 获取登录信息
username, password = get_username_password()
# 登录sql
login_sql = "select * from u_p where username='%s' and password = '%s'" % (username, password)
print(login_sql)
row = cursor.execute(login_sql)
if not row: return f"{username} 还没有注册,请先注册或者更换登陆信息"
return f"{username} 登录成功"
# 功能字典
func_dict = {
"1": register,
"2": login
}
while True:
print("登陆注册模拟器".center(40, "="))
# 输入选择
choice = input("输入【1】注册,【2】登录,【q】退出:>>>").strip()
# 选择退出
if choice.lower() == 'q': break
# 选择错误
if not choice.isdigit() or not func_dict.get(choice): continue
res = func_dict.get(choice)()
print(res)
# 关闭游标和连接
cursor.close()
conn.close()
================登陆注册模拟器=================
输入【1】注册,【2】登录,【q】退出:>>>2
当前还没有用户注册,请先注册
================登陆注册模拟器=================
输入【1】注册,【2】登录,【q】退出:>>>1
用户名:>>>bruce
密码:>>>000
bruce 注册成功
================登陆注册模拟器=================
输入【1】注册,【2】登录,【q】退出:>>>1
用户名:>>>bruce
密码:>>>000
bruce 已经注册,请更换用户名或者登录
================登陆注册模拟器=================
输入【1】注册,【2】登录,【q】退出:>>>2
用户名:>>>bruce
密码:>>>000
bruce 登录成功
================登陆注册模拟器=================
输入【1】注册,【2】登录,【q】退出:>>>q
bruce' -- 任意内容
================登陆注册模拟器=================
输入【1】注册,【2】登录,【q】退出:>>>2
用户名:>>>bruce' -- aaa
密码:>>>456
bruce' -- aaa 登录成功
任意字符' or 1=1 -- 任意内容
================登陆注册模拟器=================
输入【1】注册,【2】登录,【q】退出:>>>2
用户名:>>>tom' or 1=1 -- a
密码:>>>456
tom' or 1=1 -- a 登录成功
# 登录sql
login_sql = "select * from u_p where username='%s' and password = '%s'" % (username, password)
print(login_sql)
select * from u_p where username='bruce' -- aaa' and password = 'aaa'
username='bruce'
的后面--
select * from u_p where username='tom' or 1=1 -- a' and password = '456'
username='tom'
的后面1=1
--
1=1
# 登录
def login():
# 先判断是否有人注册
row = cursor.execute('select * from u_p;')
if not row: return "当前还没有用户注册,请先注册"
# 获取登录信息
username, password = get_username_password()
# 登录sql
login_sql = "select * from u_p where username=%s and password = %s"
row = cursor.execute(login_sql, (username, password))
if not row: return f"{username} 还没有注册,请先注册或者更换登陆信息"
return f"{username} 登录成功"
ROLLBACK
语句或者使用数据库连接对象的 rollback()
方法来回滚事务。import pymysql
# 创建数据库连接
connection = pymysql.connect()
# 创建游标
cursor = connection.cursor()
try:
# 开始事务
connection.begin()
# 执行一些数据库操作
cursor.execute("", (value, ))
# 提交事务
connection.commit()
except Exception as e:
# 发生异常时回滚事务
print(f"Error: {e}")
connection.rollback()
finally:
# 关闭游标和连接
cursor.close()
connection.close()