我有一个字典列表,在清理数据后作为参数传递给updateResource()。
#method to clean the dictionary data
def getResource(self):
try:
for i in range(len(data)):
sys_name = data[i]["system_name"]
team = data[i]["fdc_inv_sa_team"]
sys_name = re.sub('.1DC.com|.1dc.com|.1dc.COM |.1DC.COM\\b', '', str(sys_name))
sys_name = str(sys_name.strip('"[]"'))
team = str(team).replace('\\n', '')
team = str(str(team).strip("[]"))
data[i]["system_name"] = sys_name
data[i]["fdc_inv_sa_team"] = team
return data
except Exception, e:
logger.error("Error : ", str(e))
以下是将字典列表作为参数并在执行一些检查后更新数据库的方法。
#method to update the database with the dictionary key-value pair.
def updateResource(self, data):
for i in range(len(data)):
self.arg1 = data[i]["system_name"]
self.arg2 = data[i]["fdc_inv_sa_team"]
try:
query1_row = self.cursor.execute(self.select_query %self.arg1)
if query1_row:
print "Success"
else:
self.cursor.execute(self.insert_query, (self.arg1, self.arg2, "Resource Not Present In Echo_Resource Table", \
str(datetime.now())))
self.cnx.commit()
except MySQLdb.Error as e:
logger.error("Error %d: %s" % (e.args[0],e.args[1]))
except Exception, e:
logger.error("Error : ", str(e))
以下是示例查询 -
select_query = "SELECT resource_id, resource_name, support_contact_id \
FROM echo_resource \
WHERE resource_name = (%s) \
AND inactive = 0;"
update_query = "UPDATE echo_resource \
SET support_contact_id = ( \
SELECT contact_id FROM contacts WHERE last_name = (%s)), \
update_date = (%s) \
WHERE resource_name = (%s);"
contact_echo_resource_query = "SELECT 1 \
FROM echo_resource \
WHERE resource_name = (%s) \
AND support_contact_id = (SELECT contact_id \
FROM contacts \
WHERE last_name = (%s));"
contacts_query = "SELECT 1 \
FROM contacts \
WHERE last_name = (%s);"
insert_query = "INSERT INTO echo_resource_log VALUES(%s, %s, %s, %s);"
echo_resource表的结构 -
resource_id varchar(40) NO PRI
resource_name varchar(255) YES MUL
description longtext YES
ip_address varchar(40) YES
resource_tag varchar(40) YES
support_contact_id int(11) YES MUL
last_found_date_time datetime YES
错误讯息 -
[2017-07-17 18:14:31,794] {updateEchoResource.py:82} DEBUG - Arguments for the queries : n3bvap049, X2Linux_NSS
[2017-07-17 18:14:31,795] {updateEchoResource.py:121} ERROR - Error 1054: Unknown column 'n3bvap049' in 'where clause'
答案 0 :(得分:1)
很明显,因为您在列值周围缺少单引号''
,因此它也被视为列名
WHERE resource_name = (%s) \
^...here
因此,您必须更好地使用查询(OR)连接您的值,并使用参数化查询