Python:为列和值设置参数 pypyodbc - executemany

标签 python sql-server database pypyodbc

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

COLUMNS = [['NAME','SURNAME','AGE'],['SURNAME','NAME','AGE']]
VALUES = [['John','Doe',56],['Doe','John',56]]
TABLE = 'people'

这是我想传递的方式,但它不起作用:

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()

最佳答案

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

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

引用资料:

关于Python:为列和值设置参数 pypyodbc - executemany,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44941926/

相关文章:

python - 使用 pyserial 从串行读取输出。

Python 3 - 元组超出范围错误。但我用的是字典?

sql - i-batis中动态列名、目标表以及动态where条件的select查询

sql-server - 临时表、列名称或提供的值的数量与表定义不匹配

mysql - 我可以在Windows 7上运行不同版本的mysql吗

php - 键->值数据有哪些好的、快速的持久存储选项?

python - 如何在函数中获取按钮文本 - tkinter?

sql-server - 暂停 Azure 功能,直到 Entity Framework 进行更改

尝试在同一连接内运行多个命令时出现 C# Winforms Npgsql 3.0.5 "An operation already in progress"错误

python - 子进程,在 Python 的替代版本中启动脚本