提问者:小点点

python flask中带空格的postgresql表数据的动态更新


我的问题是,

  engine = create_engine("postgres://")
  conn = engine.connect()
  conn.autocommit = True

在烧瓶路由中,我使用这个查询,

  result = conn.execute("""UPDATE business_portal SET business_name ="""+str(business_name)+""", name_tag ="""+str(business_tag)+""",name_atr = """+str(business_attr)+""", address =""" +str(address)+""",address_tag =""" +str(address_tag)+""", address_atr = """+str(address_attr)+""", city = """+str(city)+""", city_tag ="""+str(city_tag)+""", city_atr =""" +str(city_attr)+""", state = """+str(state)+""", state_tag = """+str(state_tag)+""",state_atr = """+str(state_attr)+""",zip_code = """+str(zipcode)+""",zip_tag ="""+str(zip_tag)+""",zip_atr ="""+str(zip_attr)+""",contact_number ="""+str(contact_number)+""",num_tag = """+str(contact_tag)+""", num_atr ="""+str(contact_attr)+""",domain ="""+str(domain)+""", search_url = """+str(search_url)+""",category =""" +str(category)+""", logo_path =""" +str(logo_path)+""" WHERE id=%s """,(id))

上面的查询接受没有空格的数据(例如abcd)。。。。 但是当数据包含空格时(如abcd,efgh,ijkl),它会显示语法错误。

有人能帮我吗?


共1个答案

匿名用户

SET子句中的for值需要以与WHERE子句中的值相同的方式引用。

>>> cur = conn.cursor()
>>> stmt = "UPDATE postings SET custno = %s WHERE id = %s"
>>>
>>> # Observe that the SET value is three separate characters
>>> cur.mogrify(stmt % ('a b c', 37))
b'UPDATE tbl SET col = a b c WHERE id = 42'
>>>
>>> # Observe that the SET value is a single, quoted value
>>> cur.mogrify(stmt,  ('a b c', 37))
b"UPDATE tbl SET col = 'a b c' WHERE id = 42"

NBcursor.mogrify是一个psycopg2方法,用于打印将由cursor.execute发送到服务器的查询:它实际上并不执行查询。