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'

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))
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)
)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.