发布时间:2019-08-17 08:49:47编辑:auto阅读(2295)
github上的小练习啦,生成激活码,并且保存到mysql数据库中,代码:
#coding=utf-8
import uuid
import pymysql
'''
uuid库生成128位全局唯一标识符
'''
#生成num个验证码,每个验证码长度位length,可设置默认长度
def create_num(num,length=16):
result=[]
while num>0:
uuid_id=uuid.uuid1()
temp=str(uuid_id).replace('-','')[:length]
if temp not in result:
result.append(temp)
num-=1
return result
def save_to_mysql(code):
conn=pymysql.connect(
host='127.0.0.1',
port=3306,
user='root',
passwd='root',
db='test')
try:
with conn.cursor() as cursor:
#获取操作游标
sql="INSERT INTO `codes`(`code`)VALUES(%s)"
cursor.execute(sql,code)
conn.commit()
with conn.cursor() as cursor:
sql="SELECT `id`,`code` FROM `codes` WHERE `code`=%s"
cursor.execute(sql,code)
# 使用 fetchone() 方法获取一条数据库
result=cursor.fetchone()
print(result)
finally:
conn.close()
for code in create_num(200):
save_to_mysql(code)
学习笔记:
1、uuid库,python使用UUID库生成128位的全局唯一标识符。
2、使用python进行mysql的库主要有三个:MySQLdb,PyMySQL和SQLAlchemy。
Python-MySQL资格最老,核心由C语言打造,接口精炼,性能最棒,缺点是环境依赖较多,安装复杂,近两年已停止更新,只支持Python2,不支持Python3。
PyMySQL为替代Python-MySQL而生,纯python打造,接口与Python-MySQL兼容,安装方便,支持Python3。
SQLAlchemy是一个ORM框架,它并不提供底层的数据库操作,而是要借助于MySQLdb、PyMySQL等第三方库来完成,目前SQLAlchemy在Web编程领域应用广泛。
本例用的是PyMySQL,代码是很典型的数据库操作。
上一篇: python基础学习04(死循环)
下一篇: Python3安装与配置venv虚拟环境
48881
47955
38732
35872
30296
27057
26081
20915
20725
19087
542°
627°
630°
636°
606°
587°
663°
729°
852°
972°