美文网首页
pymysql操作数据库

pymysql操作数据库

作者: Mikasa___ | 来源:发表于2020-04-19 21:55 被阅读0次
import pymysql
import json
import os

#科室为中医皮肤科用户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
#经典版病历夹信鸽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\"'

#数据库信息
token_db = {略}
uas_db = {略}

#数据库连接
def db_con(db):
    con = pymysql.connect(**db)     #当db是字典类型时,以关键字参数类型传参
    return con

#数据库连接关闭
def db_close(con):
    con.close()

#查找所有内容
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)
    #绑定后再次查找数据库,核对绑定数量
    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 = '此次共计绑定token%s个,绑定失败%s个,原有已存在token%s个' % (bind,failcount,hasbound)
    log(ids)
    db_close(tokco)
    db_close(uasco)

遇到的问题及总结:


image.png
def fun(a,b,*c,**d):     #*args表示位置参数,可以是任何多个无名参数,*args 会将参数打包成tuple给函数体调用;**kwargs表示关键字参数,它将参数打包成dict给函数调用。
    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') 位置参数,是元组
                                            #输出 {'y': 2, 'x': 1} 关键字参数,是字典
    function(a=2)           #输出 {'a':2} <class 'dict'>

总结如下:

  • function(name='xx',color='yy')
    可以用 字典打包参数传给函数,传参类型是(两个星号)kwargs
    dicname={'name':'xx','color'='yy'}
    function(**dicname) 和 function(name='xx',color='yy')作用相同

  • 数据库查出来的数据类型是元组,利用角标获取到元素和sql字符串拼接时可以不用转格式,%后面直接跟元素

  • sql语句传参引用元素时注意变量值要加双引号,注意双引号要转义

  • 在循环里不要同名变量拼接/引用后再次赋值,如下图user_find_sql 再次循环会产生格式问题,怀疑是把上个循环内容累加了,修改了变量名解决了

image.png

相关文章

网友评论

      本文标题:pymysql操作数据库

      本文链接:https://www.haomeiwen.com/subject/kpevbhtx.html