Reputation: 431
I want to add the data in MySQL database using python 2.7 on CentOS.
Here's my code,
# 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()
I am getting the error below,
_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")
I am able to the data manually in db using,
cur.execute ("INSERT INTO test_release_score
(portalCluster,portalVersion,portalDomain) values ('%s', %s, '%s')"
% ("1122q", 7, "2wq2w"))
But, when I change it to something like below
# change 7 to 'qa22'
cur.execute ("INSERT INTO test_release_score
(portalCluster,portalVersion,portalDomain) values ('%s', %s, '%s')" %
("1122q", "qa12", "2wq2w"))
I get the error:
_mysql_exceptions.OperationalError: (1054, "Unknown column 'qa12' in 'field list'")
Any help would be appreciated.
Upvotes: 1
Views: 71
Reputation: 149804
Instead of interpolating the values into the query with the %
operator, use placeholders and query parameters:
query = ("INSERT INTO test_score (portalCluster,portalVersion,portalDomain) "
"VALUES (%s, %s, %s)")
cur.execute(query, (clusterList[i], versionList[i], portalDomains[i]))
This way the database driver will do the necessary escaping/quoting for you, which also prevents SQL-injection vulnerabilities.
Upvotes: 2