Advertisement
Guest User

Untitled

a guest
Apr 1st, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. import psycopg2
  2. try:
  3. #Define connection
  4. connection = psycopg2.connect(user = "postgres",
  5. password = "xxxxxx",
  6. host = "127.0.0.1",
  7. port = "5432",
  8. database = "crudseries")
  9. cursor = connection.cursor()
  10. cake_id = 2
  11. cake_type = 'Passion'
  12.  
  13. #Get record as it is pre edit
  14. print("Table Records")
  15. select = """SELECT * FROM stage1.cake_flavours
  16. where cake_id = %s;"""
  17.  
  18. cursor.execute(select, (cake_id, ))
  19. record = cursor.fetchone()
  20. print(record)
  21.  
  22. # Update the record
  23. update = """Update stage1.cake_flavours set cake_type = %s where cake_id = %s"""
  24. cursor.execute(update, (cake_type, cake_id))
  25. connection.commit()
  26. count = cursor.rowcount
  27. print(count, "Record Updated successfully ")
  28.  
  29. #Print Updated Record
  30. newselect = """SELECT * FROM stage1.cake_flavours where cake_id = %s"""
  31. cursor.execute(newselect, (cake_id,))
  32. record = cursor.fetchone()
  33. print(record)
  34.  
  35.  
  36. #Execute
  37. cursor.execute(query, record)
  38. connection.commit()
  39. count = cursor.rowcount
  40. print(count, "Record Inserted successfully!")
  41. except (Exception, psycopg2.Error) as error :
  42. print ("Error encountered while Inserting Record :-(", error)
  43. finally:
  44. #Close DB connection.
  45. if(connection):
  46. cursor.close()
  47. connection.close()
  48. print("Postgres connection has been closed")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement