0

Myquery is inserted if i give the static value in fields.but throws exception if i give the variable name. My Working code

import MySQLdb
import datetime

db = MySQLdb.connect("localhost","root","pass","selvapractice" )

cursor = db.cursor()

sql = "INSERT INTO selva(name) \
       VALUES ('Selva') " 
try:
   cursor.execute(sql)
   db.commit()
except: 
   print "dffds"
   db.rollback()

db.close()

My Exception Code

import MySQLdb
import datetime

db = MySQLdb.connect("localhost","root","pass","selvapractice" )

cursor = db.cursor()
a="surya"
sql = "INSERT INTO selva(name) \
       VALUES (%s) " %(a)
try:
   cursor.execute(sql)
   db.commit()
except: 
   print "dffds"
   db.rollback()

db.close()

It prints dfffds

How to give the variable name in query?Any help will be greatly appreciated!

5
  • Nothing at all like that. Commented Sep 24, 2014 at 4:28
  • i checked it prints dfffds in except block Commented Sep 24, 2014 at 4:33
  • halfcooked.com/presentations/osdc2006/python_databases.html Commented Sep 24, 2014 at 4:36
  • @Ignacio,I found out the mistake,the issus is i put (%s) instead of ('%s').now i added the single quotes in my query it works fine.Thanks for your help to identify the problem. Commented Sep 24, 2014 at 4:46
  • That's not how to fix it. That's how you create an insecure system. Commented Sep 24, 2014 at 4:47

2 Answers 2

2

Try this: Note how I am passing the variable as a param to the execute function, this is better to prevent sql injection attacks.

import MySQLdb
import datetime

db = MySQLdb.connect("localhost","root","pass","selvapractice" )

cursor = db.cursor()
a="surya"
b="male"
sql = "INSERT INTO selva(name, gender) VALUES (%s, %s)"
try:
   cursor.execute(sql, [a, b])
   db.commit()
except: 
   print "dffds"
   db.rollback()

db.close()
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks,It's works.can you give any example for giving one or more variables in query?
Just updatd my example with two variables, does that help?
0

Try

INSERT INTO table_name (name) VALUES ('selva')

2 Comments

you gave the static values for name.This query works for me.My question is how to give variable name instead of static value (selva)
INSERT INTO table_name (name) VALUES ('$name')

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.