使用python在mysql中添加数据

lnlaulya  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(326)

我想在centos上使用Python2.7在mysql数据库中添加数据。
这是我的密码,


# Sample data

clusterList =['a', 'w', 'e', 'r']
versionList = [1,2,3,4]
portalDomain = ['aa', 'bb', 'cc', 'dd']
portalDomains = ['p1', 'p2', 'p3', 'p4']

db = mysql.connect(host="mydb.com", user="nod", passwd="", db="noc")
cur = db.cursor()

for i in range(len(portalDomains)):
print("Adding data...")
query = "INSERT INTO test_score (portalCluster,portalVersion,portalDomain) values 
    ('%s', %s, '%s')" 
    % (clusterList[i], versionList[i], portalDomains[i])

cur.execute(query)
db.commit()

我得到下面的错误,

_mysql_exceptions.ProgrammingError: (1064, "You have an error in your 
SQL syntax; check the manual that corresponds to your MySQL server version for 
the right syntax to use near 'release-20180822-16, 'portal.xyv.com')' at line 1")

我可以使用,

cur.execute ("INSERT INTO test_release_score 
(portalCluster,portalVersion,portalDomain) values ('%s', %s, '%s')" 
% ("1122q", 7, "2wq2w"))

但是,当我把它改成下面这样的东西


# change 7 to 'qa22'

cur.execute ("INSERT INTO test_release_score 
(portalCluster,portalVersion,portalDomain) values ('%s', %s, '%s')" % 
("1122q", "qa12", "2wq2w"))

我得到一个错误:

_mysql_exceptions.OperationalError: (1054, "Unknown column 'qa12' in 'field list'")

任何帮助都将不胜感激。

5lwkijsr

5lwkijsr1#

而不是使用 % 运算符,使用占位符和查询参数:

query = ("INSERT INTO test_score (portalCluster,portalVersion,portalDomain) "
         "VALUES (%s, %s, %s)") 
cur.execute(query, (clusterList[i], versionList[i], portalDomains[i]))

这样,数据库驱动程序将为您执行必要的转义/引用,这也可以防止sql注入漏洞。

相关问题