postgresql cursor.execute("INSERT INTO im_entry.test ("+entrym+") VALUES ('"+p+"');")
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5342698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
cursor.execute("INSERT INTO im_entry.test ("+entrym+") VALUES ('"+p+"');")
提问by Ria
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.
我使用这样的,在那里查询entry1
,entry2
等等都是我的数据库表。该程序没有显示任何错误,但该p
值没有插入到数据库中。这里有什么问题?请帮我。
回答by intgr
By default, psycopg2starts 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
.
默认情况下,psycopg2会自动为您启动事务,这意味着您必须告诉它提交。请注意,这commit
是 的方法,而connection
不是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 attackspossible.
否则,您可能会冒着使SQL 注入攻击成为可能的风险。