安装,导入
pip3 install pymysql
import pymysql
链接数据库
conn = pymysql.connect(
host=“你的数据库地址”,
user=“用户名”,password=“密码”,
database=“数据库名”,
charset=“utf8”) # 不能为utf-8
创建光标对象
得到一个可以执行SQL语句的光标对象
执行完毕返回的结果集默认以元组显示
cursor = conn.cursor()
得到一个可以执行SQL语句并且将结果作为字典返回的游标
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
执行sql语句
cursor.execute()
# 3、执行sql语句
# a.sql语句固定死了
# sql1 = 'SELECT * FROM member WHERE mobile_phone = "13734076707";'
# sql2 = 'SELECT * FROM member ORDER BY id DESC LIMIT 0,5;'
one_mobile = input("请输入您的手机号!")
# sql3 = f'SELECT * FROM member WHERE mobile_phone = {one_mobile};'
# b.给sql语句添加参数,%s为占位符
sql3 = 'SELECT * FROM member WHERE mobile_phone = %s;'
#cursor.execute(sql1)
# cursor.execute(sql2)
# cursor.execute(sql3)
# c.执行sql语句时,给sql语句传递参数,args为序列类型,参数与sql语句中的%s,一一对应
cursor.execute(sql3, args=[one_mobile])
获取值并提交
fetchone获取一条数据,如果游标类为DictCursor,则结果为字典类型
fetchall获取多条数据,如果游标类为DictCursor,则结果为嵌套字典的列表类型
result = one_cursor.fetchone()
result = one_cursor.fetchall()
提交结果
conn.commit()
关闭连接
a.必须先关游标
b.再关连接
one_cursor.close()
conn.close()
案例
import pymysql
import random
from frame_test.scripts.handle_yaml import do_yaml
class HandleMysql:
"""
执行sql语句
"""
def __init__(self):
# 链接数据库,do_yaml.get_data读取yaml文件中数据
self.conn = pymysql.connect(host=do_yaml.get_data('mysql', 'host'),
user=do_yaml.get_data('mysql', 'user'),
password=do_yaml.get_data('mysql', 'password'),
db=do_yaml.get_data('mysql', 'db'),
port=do_yaml.get_data('mysql', 'port'),
charset='utf8', # 这里只能写为utf8
cursorclass=pymysql.cursors.DictCursor)
# 创建游标对象
self.cursor = self.conn.cursor()
def get_one_value(self, sql, args=None):
"""
执行sql语句,获取单条数据
"""
self.cursor.execute(sql, args=args)
self.conn.commit()
return self.cursor.fetchone()
def get_values(self, sql, args=None):
"""
执行sql语句,获取多条数据
"""
self.cursor.execute(sql, args=args)
self.conn.commit()
return self.cursor.fetchall()
def close(self):
"""
关闭游标,链接
"""
self.cursor.close()
self.conn.close()
@staticmethod
def create_mobile():
"""
随机生成11位手机号
:return: 返回一个手机号字符串
"""
start_mobile = ['138', '139', '188']
start_mobile = random.choice(start_mobile)
#random.sample 随机选取8位数
end_num = ''.join(random.sample('0123456789', 8))
return start_mobile + end_num
def is_existed_mobile(self, mobile):
"""
判断指定的手机号在数据库中是否存在,若存在则执行登录
:param mobile: 11位手机号组成的字符串
:return: True or False
"""
# sql = "SELECT username FROM yujia.cust_user_login_fail WHERE mobile=%s;"
sql = do_yaml.get_data('mysql', 'select_user_sql')
if self.get_one_value(sql, args=[mobile]): # 手机号已经存在,则返回True,否则返回False
return True
else:
return False
def create_not_existed_mobile(self):
"""
判断指定的手机号在数据库中是否存在,若不存在则执行注册
随机生成一个在数据库中不存在的手机号
:return: 返回一个手机号字符串
循环,当未注册的手机号码时才跳出循环
"""
while True:
one_mobile = self.create_mobile()
if not self.is_existed_mobile(one_mobile):
break
return one_mobile
if __name__ == '__main__':
do_mysql = HandleMysql()
print(do_mysql.get_not_existed_user_id())
print(do_mysql.create_not_existed_mobile())
print(do_mysql.is_existed_mobile("18317778810"))