【问题标题】:cursor.execute("INSERT INTO im_entry.test ("+entrym+") VALUES ('"+p+"');")cursor.execute("INSERT INTO im_entry.test ("+entrym+") VALUES ('"+p+"');")
【发布时间】:2011-07-17 14:16:08
【问题描述】:
   entrym='entry'
   entrym=entrym+ str(idx)

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

我正在使用这样的查询,其中entry1entry2 等是我的数据库表。该程序没有显示任何错误,但p 值没有插入到数据库中。这里有什么问题?请帮我。

【问题讨论】:

    标签: python database postgresql


    【解决方案1】:

    默认情况下,psycopg2 会自动为您启动事务,这意味着您必须告诉它提交。注意commitconnection 的方法,而不是cursor

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

    目的是您可以在一个事务中将多个语句组合在一起,这样其他查询就不会看到一半的更改,但也是出于性能原因。

    另外请注意,您应该始终使用占位符,而不是将字符串连接在一起。
    例如:

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

    否则,您将面临使SQL injection attacks 成为可能的风险。

    【讨论】:

    • 我的 colname 在循环中变化(entry1、entry2..etc)那么我该如何编写查询
    • @Ria cur.execute("INSERT INTO im_entry.test (%s) VALUES (%s)", [colname,p]) 甚至 cur.execute("INSERT INTO im_entry.test (entry%s) VALUES (%s)", [idx,p])
    • @Ria 听起来你正在尝试做一些奇怪的事情。通常,您总是会从单个代码路径中插入相同的列。这是一个很大的话题,但您应该研究数据库规范化。
    猜你喜欢
    • 2010-10-26
    • 2012-07-06
    • 2015-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多