zoukankan      html  css  js  c++  java
  • python 使用 pymysql 存,改dic类型数据

    公司以前用的 django 的 orm ,后来为了解耦,想着改用mysql存数据,好久没用过了。踩到的坑,大家可以参考一下。 个人感觉还是mongodb好用。

    注意 每条sql最后 一定要有 冒号 ;

    from dmp.mysql_demo.utils import MY_POOL
    import pymysql
    
    
    def create_conn():  # 连接池
        conn = MY_POOL.connection()
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        return conn, cursor
    
    
    def new_update_one(dic, table_name, ziduan, zd):
        '''
    
        :param dic:   存入的 dic 数据
        :param table_name:  存入的表名
        :param ziduan:  修改的字段
        :param zd:      字段内容
        :return:         返回值
        '''
        conn, cur = create_conn()
        new_sql = f"update  {table_name} set "  # 增加
        del dic[ziduan]
        for key in dic:
            if "id" in key:
                new_sql += f" {key}={dic[key]} ,"
            else:
                new_sql += f" {key} = '{dic[key]}' ," # 每个修改的字段 要用' ,' 隔开
        new_sql = new_sql[:-1]   # 去掉最后的 ,
        new_sql += f" where {ziduan} = '{zd}' ;" # 加上修改条件 
        result = cur.execute(new_sql)
        conn.commit()
        close_conn(conn, cur)
        return result
    
    
    def new_insert_one(dic, table_name):
        '''
        :param dic:  存入的 dic 数据
        :param table_name:   表名
        :return:    返回值
        '''
        print('new insert one: ', dic)
        new_sql = f"insert into {table_name} {tuple(dic.keys())}"  # 增加
        print('new_sql: ', new_sql)
        sql = new_sql.replace("'", "")  # sql 中 字段不能带 "引号" 所以去掉
        sql += f"VALUE {tuple(dic.values())} ;"
        conn, cur = create_conn()
        result = cur.execute(sql)
        conn.commit()
        close_conn(conn, cur)
        return result
    
    
  • 相关阅读:
    ie6内存泄漏问题的解决
    精简版拖动
    【转】在ASP.Net中写系统日志
    转 集中遍历遍历datatable的方法
    水晶报表字段为空时设置默认值
    数据库一种IN查询
    两种获得路径的测试
    整理——ASP.net UTF8支持
    Subversion svnserve 服务配置 整理
    [转自CSDN] SQL基础> 约束(CONSTRAINT)
  • 原文地址:https://www.cnblogs.com/wzbk/p/14636832.html
Copyright © 2011-2022 走看看