Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

python - cursor.execute("INSERT INTO im_entry.test ("+entrym+") VALUES ('"+p+"');")

   entrym='entry'
   entrym=entrym+ str(idx)

   cursor.execute("INSERT INTO im_entry.test ("+entrym+") VALUES ('"+p+"');")

I am using a query like this, where entry1, entry2 etc. are my database tables. The program doesn't show any errors, but the p value does not get inserted in the db. What is wrong here? Please help me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

By default, psycopg2 starts transactions for you automatically, which means that you have to tell it to commit. Note that commit is a method of the connection, not the cursor.

conn = psycopg2.connection('...')
cur = conn.cursor()
cur.execute("...")
conn.commit()

The intent is that you can group multiple statements together in a single transaction, so other queries won't see half-made changes, but also for performance reasons.

Also note that you should always use placeholders, instead of concatenating strings together.
E.g.:

cur.execute("INSERT INTO im_entry.test (colname) VALUES (%s)", [p])

Otherwise you risk making SQL injection attacks possible.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...