• python mysql插入数据遇到的错误


    1.数据插入的时候报错:not enough arguments for format string,大概意思就是说没有足够的参数格式化字符串。

    我的数据库插入方法是这样的

        def add_data(self,data_dic):
            tables = 'user'
            keys = ','.join(data_dic.keys())
            values = ','.join(['%s'] * len(data_dic))
            sql =f'INSERT INTO {tables} ({keys}) VALUES({values}) ON DUPLICATE KEY UPDATE '
            update = ','.join([f"{k}='{v}'" for k,v in data_dic.items()])
            sql += update
            try:
                if self.cursor.execute(sql, tuple(data_dic.values())):
                    print('ok')
                    self.conn.commit()
            except Exception as e:
                print(e.args)
                self.conn.rollback()
            self.conn.close()
    

      通过调试我得知程序在执行cursor.execute的时候报了该错误。

    为了进一步了解原因,我找到了关于实现execute的方法:

        def mogrify(self, query, args=None):
            """
            Returns the exact string that is sent to the database by calling the
            execute() method.
    
            This method follows the extension to the DB API 2.0 followed by Psycopg.
            """
            conn = self._get_db()
            if PY2:  # Use bytes on Python 2 always
                query = self._ensure_bytes(query, encoding=conn.encoding)
    
            if args is not None:
                query = query % self._escape_args(args, conn)
    
            return query
    

      通过上面的方法可以的得知,关键的一句话是

    query = query % self._escape_args(args, conn)
    

     我要插入最后一个字段中有其中一段文字

    厨房和体育健身用品等进口关税平均税率由 15.9%降至7.2%
    

      因为%的原因出错了,所以我尝试这把上面方法修改成下面的方式 使用format去格式化字符串

      def add_data(self,data_dic):
            tables = 'user'
            keys = ','.join(data_dic.keys())
            values = ','.join(['%s'] * len(data_dic))
            sql ='INSERT INTO {tables} ({keys}) VALUES({values}) ON DUPLICATE KEY UPDATE '.format(tables=tables,keys=keys,values=values)
            update = ','.join(["{key}=%s".format(key=key) for key in data_dic])
            sql += update
            try:
                if self.cursor.execute(sql,tuple(data_dic.values())*2):
                    print('ok')
                    self.conn.commit()
            except Exception as e:
                print(e.args)
                self.conn.rollback()
            self.conn.close()
    

      

  • 相关阅读:
    EasyUI限制时间选择(开始时间小于结束时间)
    C# readonly与const的区别
    C# Lambda 表达式
    C# 扩展方法
    C# 枚举enum
    Visual Studio中的“build”、“rebuild”、“clean”的区别
    无root开热点教程
    数据库锁
    安卓:标题栏右上角添加按钮
    安卓:从assets目录下复制文件到指定目录
  • 原文地址:https://www.cnblogs.com/c-x-a/p/9207451.html
Copyright © 2020-2023  润新知