pymysql操作數(shù)據(jù)庫

import pymysql
import json
import os

#科室為中醫(yī)皮膚科用戶10799
#select * from t_user_account ac LEFT JOIN t_user_hospital_info hos on ac.user_id=hos.user_id where hos.department_id =100045
#經(jīng)典版病歷夾信鴿token 6311
#select * from device where createdTime<='2020-04-15 20:43:20' and appName = 'medchart'
#需求是把6311 token綁到10799用戶中

token_find_sql = 'select token from device where createdTime<="2020-04-15 20:43:20" and appName = "medchart" and status=1'
users_find_sql = 'select * from t_user_account ac LEFT JOIN t_user_hospital_info hos on ac.user_id=hos.user_id where hos.department_id =100045'
user_find_sql = 'select * from device where appName = "medchart" and userId = \"%s\" and status=1'
upd_sql = 'update device set userId = \"%s\" where token = \"%s\"'

#數(shù)據(jù)庫信息
token_db = {略}
uas_db = {略}

#數(shù)據(jù)庫連接
def db_con(db):
    con = pymysql.connect(**db)     #當(dāng)db是字典類型時(shí),以關(guān)鍵字參數(shù)類型傳參
    return con

#數(shù)據(jù)庫連接關(guān)閉
def db_close(con):
    con.close()

#查找所有內(nèi)容
def fetch_all(con,find_sql):
    cursor = con.cursor()
    cursor.execute(find_sql)
    all_found = cursor.fetchall()
    return all_found

#更新表(綁定找到的userid和token)
def update_db(con,upd_sql):
    cursor = con.cursor()
    cursor.execute(upd_sql)
    updated = con.commit()
    return updated

#保存日志
if os.path.exists('log.txt'):
    os.remove('log.txt')
def log(ids):
    with open('log.txt','a') as f:
        f.writelines(str(ids)+'\n')

if __name__=='__main__':

    tokco = db_con(token_db)
    uasco = db_con(uas_db)
    tokens = fetch_all(tokco,token_find_sql)
 
    users = fetch_all(uasco,users_find_sql)

    #useid綁定前,查找device表是否有userid,有則不綁定,無則綁定
    hasbound = 0
    bind = 0
    for i in range(0,len(tokens)):
        print(users[i][0])
        print(tokens[i][0])
        sql = user_find_sql % (users[i][0])
        print(sql)

        if fetch_all(tokco,sql):
            hasbound += 1

        else:
            bind +=1
            upd = upd_sql % (users[i][0], tokens[i][0])
            print(upd)
            update_db(tokco,upd)
            ids = '已綁定userid:%s和token:%s' % (users[i][0],tokens[i][0])
            print(ids)
            log(ids)
    #綁定后再次查找數(shù)據(jù)庫,核對綁定數(shù)量
    failcount = 0
    for i in range(0,len(tokens)):
        sql = user_find_sql % (users[i][0])
        if users[i][0] in fetch_all(tokco, sql):

            continue
        else:
            failcount +=1
            ids = '綁定失敗userid%s' % (users[i][0])
            log(ids)


    ids = '此次共計(jì)綁定token%s個(gè),綁定失敗%s個(gè),原有已存在token%s個(gè)' % (bind,failcount,hasbound)
    log(ids)
    db_close(tokco)
    db_close(uasco)

遇到的問題及總結(jié):


image.png
def fun(a,b,*c,**d):     #*args表示位置參數(shù),可以是任何多個(gè)無名參數(shù),*args 會(huì)將參數(shù)打包成tuple給函數(shù)體調(diào)用;**kwargs表示關(guān)鍵字參數(shù),它將參數(shù)打包成dict給函數(shù)調(diào)用。
    print(a);
    print(b);
    print(c);
    print(d);
def function(**kwargs):
    print( kwargs, type(kwargs))

if __name__ == '__main__':
    fun(2,3,'haha','hehe','hoho',x=1,y=2)   # 輸出2
                                            # 輸出3
                                            # 輸出('haha', 'hehe', 'hoho') 位置參數(shù),是元組
                                            #輸出 {'y': 2, 'x': 1} 關(guān)鍵字參數(shù),是字典
    function(a=2)           #輸出 {'a':2} <class 'dict'>

總結(jié)如下:

  • function(name='xx',color='yy')
    可以用 字典打包參數(shù)傳給函數(shù),傳參類型是(兩個(gè)星號)kwargs
    dicname={'name':'xx','color'='yy'}
    function(**dicname) 和 function(name='xx',color='yy')作用相同

  • 數(shù)據(jù)庫查出來的數(shù)據(jù)類型是元組,利用角標(biāo)獲取到元素和sql字符串拼接時(shí)可以不用轉(zhuǎn)格式,%后面直接跟元素

  • sql語句傳參引用元素時(shí)注意變量值要加雙引號,注意雙引號要轉(zhuǎn)義

  • 在循環(huán)里不要同名變量拼接/引用后再次賦值,如下圖user_find_sql 再次循環(huán)會(huì)產(chǎn)生格式問題,懷疑是把上個(gè)循環(huán)內(nèi)容累加了,修改了變量名解決了

image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容