【发布时间】: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