0

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

2
  • Take the % out of the sql statement, hence it should be sql = """INSERT INTO table1(username,gender,age,password,id) VALUES(%s,%s,%s,%s,%s)""" ,(urn,gdr,agex,psd,idx). Commented Jan 9, 2018 at 15:04
  • It works now. Thanks a lot. Commented Jan 9, 2018 at 15:10

1 Answer 1

2

You must not use string substitution. Use parameters.

sql = """INSERT INTO table1(username,gender,age,password,id) VALUES(%s,%s,%s,%s,%s)"""
cursor.execute(sql, (urn,gdr,agex,psd,idx))

That book appears to be recommending unsafe practices. You should stop reading it immediately.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh! really~ I will stop receiving the wrong messages from this book. And thanks for your suggestion. It works now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.