mysql请求中的Python变量
我是Python 3.4.6的新手: 我试图在mysql数据库中插入一些行,但带有变量。 首先,我有一个字典列表。 这是我的密码:mysql请求中的Python变量,python,mysql,mysql-python,Python,Mysql,Mysql Python,我是Python 3.4.6的新手: 我试图在mysql数据库中插入一些行,但带有变量。 首先,我有一个字典列表。 这是我的密码: import mysql.connector import time db = mysql.connector.connect(host='localhost', user='xxxxx', passwd='xxxxx', database='xxxxx') cursor = db.cursor() now_db = time.strftime('%Y-%m-%d
import mysql.connector
import time
db = mysql.connector.connect(host='localhost', user='xxxxx', passwd='xxxxx', database='xxxxx')
cursor = db.cursor()
now_db = time.strftime('%Y-%m-%d %H:%M:%S')
for key, value in list_hosts
key_db += key+", "
value_ex += "%s, "
value_db += "\""+value+"\", "
key_db = key_db.strip(" ")
key_db = key_db.strip(",")
value_ex = value_ex.strip(" ")
value_ex = value_ex.strip(",")
value_db = value_db.strip(" ")
value_db = value_db.strip(",")
add_host = ("INSERT INTO nagios_hosts (date_created, date_modified, "+key_db+") VALUES ("+value_ex+")")
data_host = ("\""+now_db+"\", \""+now_db+"\", "+value_db)
cursor.execute(add_host, data_host)
db.commit()
db.close()
列表_主机的示例:
OrderedDict([('xxxx1', 'data1'), ('xxxx2', 'data2'), ('xxxx3', 'data3'), ('xxxx4', 'data4'), ('xxxx5', 'data5'), ('xxxx6', 'data6')])
当然,我已经简化了代码。
我是这样做的,因为我的字典里从来没有这么多的条目。
我正在尝试创建如下内容:
add_host - INSERT INTO TABLE (date_created, date_modified, xxxx1, xxxx2, xxxx3, xxxx4, xxxx5, xxxx6) VALUES (%s, %s, %s, %s, %s, %s)
data_host - now, now, data1, data2, data3, data4, data5, data6
永远不会有相同数量的xxxx。。。
它们都存在于数据库中,但我不需要为词汇表中的每个项目填充每一列
当我执行时,会出现以下错误:
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'xxxxxxxxxxxxxxxxxxxxx' at line 1
我从Python开始,我认为我们也可以清理很多东西。。。不要犹豫:正如@khelwood在评论中提到的,您应该使用参数化查询 如果插入的列数不同,那么您可能更希望生成一个元组并在参数化查询中使用它 cursor.execute接受两个参数: 作为字符串的查询 参数作为元组 其思想是生成字符串和元组,并将它们传递给cursor.execute 您将需要以下内容:
list_hosts = {'xxxx1': 'data1', 'xxxx2': 'data2', 'xxxx3': 'data3', 'xxxx4': 'data4'}
keys = [] # creating a list for keys
values = () # creating a tuple for values
for key, value in list_hosts.items():
keys.append(key)
values = values + (value,)
keys_str = ', '.join(keys)
ps = ', '.join(['%s'] * len(list_hosts))
query = "INSERT INTO tbl (%s) VALUES (%s)" % (keys_str, ps)
print(query)
# INSERT INTO tbl (data_created, data_modified, xxxx1, xxxx2, xxxx3, xxxx4) VALUES (%s, %s, %s, %s)
cursor.execute(query, values)
刚刚在一个样本数据上试用过,效果很好 这里有一个标准的python3-python2兼容解决方案:
import time
from collections import OrderedDict
list_hosts = OrderedDict([("field1", "value1"), ("field2", "value2"), ("fieldN", "valueN")])
# builds a comma-separated string of db placeholders for the values:
placeholders = ", ".join(["%s"] * (len(list_hosts) + 2))
# builds a comma-separated string of field names
fields = ", ".join(("date_created","date_modified") + tuple(list_hosts.keys()))
# builds a tuple of values including the dates
now_db = time.strftime('%Y-%m-%d %H:%M:%S')
values = (now_db, now_db) + tuple(list_hosts.values())
# build the SQL query:
sql = "INSERT INTO nagio_hosts({}) VALUES({})".format(fields, placeholders)
# and safely execute it
cursor.execute(sql, values)
db.commit()
您应该使用查询参数。我知道你想在这里用value_ex和data_host做什么。查询参数?怎样我在源词典中从来没有相同数量的条目,所以我不知道要在数据库中插入多少条目。我不知道该怎么做,因为我不知道我的查询值中应该有多少%s。例如,数据主机,它只是在数据库中添加datetime,而不是由字典提供。不要在SQL查询中使用任何类型的字符串格式,这将导致SQL注入漏洞。使用中显示的方法。我已经阅读了文档。这对我没有帮助。我找不到或不明白在我的情况下该怎么做。请发布列表主机的定义或示例。