0

I want to insert values to a database using python, but it's failed. This is my code:

 try:
 cur.execute("""INSERT INTO tb_distance (objek1, objek2, distance) VALUES ('%s','%s','%d')""", (data[i].jenis, data[k].jenis, distance))
 conn.commit()
 except:
 conn.rollback()
 print 'cannot insert into database'
donkopotamus
23.4k3 gold badges58 silver badges61 bronze badges
asked Dec 16, 2015 at 5:40

2 Answers 2

1

Thank you, I fixed my problem, I replace (,) to (%) before list of values. This is my code and run well:

cur.execute("""INSERT INTO tb_distance (objek1, objek2, distance) VALUES ('%s','%s','%f')""" % (data[i].jenis, data[k].jenis, distance))
Leistungsabfall
6,4987 gold badges38 silver badges44 bronze badges
answered Dec 16, 2015 at 6:09
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for answering your question. What you have done is correct but not secure, dont format values in python code use instead this: cur.execute("""INSERT INTO tb_distance (objek1, objek2, distance) VALUES (%(objek1)s , %(objek2)s ,%(distance)s);""", {"objek1": data[i].jenis, "objek2": data[k].jenis, "distance": distance})
0

Remove quotes around the placeholders ('%s' -> %s, '%d' -> %d):

cur.execute(
 "INSERT INTO tb_distance (objek1, objek2, distance) VALUES (%s, %s, %d)",
 (data[i].jenis, data[k].jenis, distance)
)
answered Dec 16, 2015 at 5:47

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.