python3学习(十)——常用函数定义

1、数据库连接host = '118.24.3.40user = 'jxz'

password = '123456'#密码只能是字符串
db = 'jxz'
port = 3306#端口号只能是int
charset = 'utf8'#只能写utf8,不能写utf-8

import pymysql
conn = pymysql.connect(host=host,password=password,
                user=user,db=db,port=port,
                charset=charset,autocommit = True
                )#建立连接。 #增加autocommit则自动提交,那么就不需要conn.commit()

cur = conn.cursor()#建立游标
#cur.execute('select * from app_myuser limit 5;') #execute只是帮忙执行sql语句,并不获取结果
#sql = 'insert into app_myuser(username,passwd,is_admin) VALUE ("Python_lin","123456","1")'
#sql = 'select * from app_myuser;'
sql = "select COLUMN_NAME from information_schema.COLUMNS where table_name = 'app_myuser';"
cur.execute(sql)#执行sql语句
print(cur.description)#获取这个表里面的所有字段
#conn.commit()#更新语句、新增语句执行后都要 提交
#res = cur.fetchall()#获取数据库里面的所有结果。获取的结果是二维数组
# res1 = cur.fetchone()#获取数据库里面的一条结果。fetchall执行后,再执行fetchhone则无法读到内容
# print(res1)
#操作后都要关闭,避免超过最大连接数
cur.close()
conn.close()


def my_db(ip,user,password,db,sql,port=3306,chartset='utf8'): #定义一个连接数据库的函数 conn = pymysql.connect( host=ip,user=user,password=password, db=db, port=port,charset=charset,autocommit=True )#建立连接。 #增加autocommit则自动提交,那么就不需要conn.commit() cur = conn.cursor()#建立游标 cur.execute(sql)#执行sql语句 res = cur.fetchall()#获取数据库里面的所有结果。获取的结果是二维数组 cur.close() conn.close()#操作后都要关闭,避免超过最大连接数 return res

2、加盐函数

#加盐
#123456+niuhanyang(在用户注册的密码后面随机加上一串字符串再进行加密形成md5更安全)
def my_md5(s:str,salt=None):
    #salt 是盐值
    s = str(s)
    if salt:
        s = s + salt
    m = hashlib.md5(s.encode())
    print(m.hexdigest())
    return m.hexdigest
my_md5('123456','abc')

3、格式化好的时间转时间戳

def str_to_timestamp(time_str=None,format='%Y%m%d%H%M%S'):#指定默认值
    #格式化好的时间转时间戳
    #不传参的话,转当前时间
    if time_str:
        time_tuple = time.strptime(time_str, format)  # 把格式化好的时间转化成时间元祖
        timestamp = time.mktime(time_tuple)
    else:
        timestamp = time.time()
    return int(timestamp)
print(str_to_timestamp())
print(str_to_timestamp('20391111175122'))
#print(str_to_timestamp('2018-09-09','%Y%m%d%H%M%S')) #报错格式不匹配

4、时间戳转格式化好的时间

def timestamp_to_strtime(timestamp = None,format='%Y%m%d %H-%M-%S'):
    #这个函数是用来把时间戳转成格式化好的时间
    #如果不传时间戳的话,那么久返回当前的时间
    if timestamp:
        time_tuple = time.localtime(timestamp)
        str_time = time.strftime(format,time_tuple)
    else:
        str_time = time.strftime(format)
    return str_time
timestamp_to_strtime()

猜你喜欢

转载自www.cnblogs.com/xm-sunnylin/p/9764774.html