简体   繁体   中英

Dynamic update in postgresql table data with spaces in python flask

My Query is,

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

In Flask Route i am using this query,

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

The above query accepts the data without space (eg abcd).... But when data are with spaces (eg abcd efgh ijkl) it displays a syntax error.

Can any one help me?

The values for in the SET clause need to be quoted in the same way as the values in the WHERE clause.

>>> cur = conn.cursor()
>>> stmt = "UPDATE tbl SET col = %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"

NB cursor.mogrify is a psycopg2 method that prints the query that would be sent to the server by cursor.execute : it doesn't actually execute the query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM