Recently,I've got a project that I need to save variable values into a database.
I want to program a code like this:
If I want to input username="Jonh", gender="Male", age=23, password="123456789", id="11111111"
then the code looks like:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
import sys
db = MySQLdb.connect("140.120.31.124","usr1","606","testdb",port=3306 )
cursor = db.cursor()
urn="Jonh"
gdr="male"
agex="23"
psd="123456789"
idx="11111111"
sql = """INSERT INTO table1(username,gender,age,password,id) VALUES(%s,%s,%s,%s,%s)""" %(urn,gdr,agex,psd,idx)
#sql="""INSERT INTO table1(username,gender,age,password,id) VALUES("Jonh","male","23","123456789","11111111")"""
try:
cursor.execute(sql)
db.commit()
except Exception as inst:
db.rollback()
print inst
db.close()
The structure of database I set is:
username varchar(50) utf8_unicode_ci
gender varchar(50) utf8_unicode_ci
age int(2)
password varchar(20) utf8_unicode_ci
id varchar(8) utf8_unicode_ci
But, it always shows the error --> (1054, "Unknown column 'Jonh' in 'field list'")
Does anyone can help me to solve this problem? Thanks a lot.
PS. The code I refer is https://www.packtpub.com/mapt/book/big_data_and_business_intelligence/9781849510189/3/ch03lvl1sec24/using-user-defined-variables
%out of thesqlstatement, hence it should besql = """INSERT INTO table1(username,gender,age,password,id) VALUES(%s,%s,%s,%s,%s)""" ,(urn,gdr,agex,psd,idx).