【问题标题】:Python: Set param for columns and values pypyodbc - executemanyPython:为列和值设置参数 pypyodbc - executemany
【发布时间】:2017-07-06 07:04:55
【问题描述】:

我有这种情况,我创建了一个在数据库中插入行的方法。我向该方法提供列、值和表名。

列 = [['NAME','SURNAME','AGE'],['SURNAME','NAME','AGE']]
值 = [['John','Doe',56],['Doe','John',56]]
TABLE = '人'

这是我想通过的方式,但它不起作用:

db = DB_CONN.MSSQL() #method for connecting to MS SQL or ORACLE etc.
cursor = db.cursor()
sql = "insert into %s (?) VALUES(?)" % TABLE 
cursor.executemany([sql,[COLUMNS[0],VALUES[0]],[COLUMNS[1],VALUES[1]]])
db.commit()

这是它传递查询的方式,但问题是我必须有预定义的列名,这不好,因为如果另一个列表有不同的列排序怎么办?比名字中的姓氏和姓氏中的名字。

db = DB_CONN.MSSQL() #method for connecting to MS SQL or ORACLE etc.
cursor = db.cursor()
sql = 'insert into %s (NAME,SURNAME,AGE) VALUES (?,?,?)'
cursor.executemany(sql,[['John','Doe',56],['Doe','John',56]])
db.commit()

我希望我解释得足够清楚。 附言。 COLUMNS 和 VALUES 是从 json 字典中提取出来的

[{'NAME':'John','SURNAME':'Doe','AGE':56...},{'SURNAME':'Doe','NAME':'John','AGE ':77...}]

如果有帮助的话。

解决方案:

class INSERT(object):

    def __init__(self):
        self.BASE_COL = ''

    def call(self):
        GATHER_DATA =  [{'NAME':'John','SURNAME':'Doe','AGE':56},{'SURNAME':'Doe','NAME':'John','AGE':77}]
        self.BASE_COL = ''
        TABLE = 'person'

        #check dictionary keys
        for DATA_EVAL in GATHER_DATA:

            if self.BASE_COL == '': self.BASE_COL = DATA_EVAL.keys()
            else:
                if self.BASE_COL != DATA_EVAL.keys():
                    print ("columns in DATA_EVAL.keys() have different columns")
                    #send mail or insert to log  or remove dict from list
                    exit(403)

        #if everything goes well make an insert
        columns = ','.join(self.BASE_COL)
        sql = 'insert into %s (%s) VALUES (?,?,?)' % (TABLE, columns)
        db = DB_CONN.MSSQL()
        cursor = db.cursor()
        cursor.executemany(sql, [DATA_EVAL.values() for DATA_EVAL in GATHER_DATA])
        db.commit()


if __name__ == "__main__":
    ins = INSERT()
    ins.call()

【问题讨论】:

  • 如果无法确保值的顺序,您可以选择使用字典。请参阅此问题的答案stackoverflow.com/questions/9336270/… 以获得一些见解
  • 嗯我不确定,因为乍一看,这似乎不太适用于 executemany,但我会检查一下。

标签: python sql-server database pypyodbc


【解决方案1】:

您可以利用 Python 字典的键值对列表的非随机特性。 您应该检查json 记录数组中的所有项目是否具有相同的字段,否则您将在查询中遇到异常。

columns = ','.join(records[0].keys())
sql = 'insert into %s (%s) VALUES (?,?,?)' % (TABLE, columns)
cursor.executemany(sql,[record.values() for record in records])

参考资料:

【讨论】:

  • 是的,我明白了......所以基本上即使字典键在列表中的顺序不同......在我们制作循环槽字典的那一刻,它们将以相同的方式排序。谢谢,我已经与其他人分享了我的代码,以便他们可以从这个答案中受益。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-06
  • 1970-01-01
相关资源
最近更新 更多