python3學習(十) 常用函式定義

2022-05-14 14:06:11 字數 2711 閱讀 4453

1、資料庫連線host = '

118.24.3.40

user = '

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()#

建立游標##

#sql = "

"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)

ifsalt:

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

'):#

指定預設值

#格式化好的時間轉時間戳

#不傳參的話,轉當前時間

iftime_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'):

#這個函式是用來把時間戳轉成格式化好的時間

#如果不傳時間戳的話,那麼久返回當前的時間

iftimestamp:

time_tuple =time.localtime(timestamp)

str_time =time.strftime(format,time_tuple)

else

: str_time =time.strftime(format)

return

str_time

timestamp_to_strtime()

Python3常用內建函式

數學相關 1.abs a 求取絕對值。abs 1 2.max list 求取list最大值。max 1,2,3 3.min list 求取list最小值。min 1,2,3 4.sum list 求取list元素的和。sum 1,2,3 6 5.sorted list 排序,返回排序後的list。6...

python3學習日記 函式

函式是組織好的,可重複使用的,用來實現單一,或相關聯功能的 段。函式能提高應用的模組性,和 的重複利用率。定義乙個函式 defsay hi name print hi name print是python的乙個內建函式函式的引數必需引數 必需引數須以正確的順序傳入函式。呼叫時的數量必須和宣告時的一樣。...

python3基礎 常用內建函式

目錄 input函式 lambda 函式 匿名函式 repr 函式 type函式 判斷變數型別 map函式 filter函式 reduce函式 捕獲的是最原始的輸入,將所 有的輸入按照字串進行處理,並返回乙個字串,不包含回車。語法 lambda arg1 agr2,argn expression 示...