Guest User

Untitled

a guest
Aug 4th, 2018
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. #basic python code for working with POSGRESQL through psycopg2
  2.  
  3.  
  4.  
  5. import psycopg2
  6.  
  7. conn = psycopg2.connect(database="testdb", user="postgres", password="pass123", host="127.0.0.1", port="5432")
  8. print("Opened database sucessfully")
  9. cur = conn.cursor()
  10.  
  11. #CREATE A TABLE
  12.  
  13. cur.execute('''
  14. CREATE TABLE COMPANY
  15. (ID INT PRIMARY KEY NOT NULL,
  16. NAME TEXT NOT NULL,
  17. AGE INT NOT NULL,
  18. ADDRESS CHAR(50)
  19. SALARY REAL);
  20. ''')
  21.  
  22. print("Table create successfully")
  23. conn.commit()
  24. conn.close()
  25.  
  26. #INSERT operation
  27.  
  28. import psycopg2
  29.  
  30. conn = psycopg2.connect(database="testdb", user="postgres", password="pass123", host="127.0.0.1", port="5432")
  31. print("Opened database sucessfully")
  32. cur = conn.cursor()
  33.  
  34. cur.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
  35. VALUES (1, 'Paul', 32, 'California', 20000.00 )");
  36.  
  37. cur.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
  38. VALUES (2, 'Allen', 25, 'Texas', 15000.00 )");
  39.  
  40. cur.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
  41. VALUES (3, 'Teddy', 23, 'Norway', 20000.00 )");
  42.  
  43. cur.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
  44. VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 )");
  45.  
  46. conn.commit()
  47. print "Records created successfully";
  48. conn.close()
  49.  
  50. #SELECT OPERATION
  51. import psycopg2
  52. conn = psycopg2.connect(database="testdb", user="postgres", password="pass123", host="127.0.0.1", port="5432")
  53. print("Opened database sucessfully")
  54. cur = conn.cursor()
  55.  
  56. cur.execute("SELECT id, name, address, salary from COMPANY;")
  57. rows = cur.fetchall() #fetch all remaining rows of a query result, returning them as a list of tuples
  58. for row in rows:
  59. print('ID = ', row[0])
  60. print('name = ', row[1])
  61. print('address = ', row[2])
  62. print('salary = ', row[3], '\n')
  63. print('Operation done");
  64. conn.close() #there is no conn.commit when executing select operation
Add Comment
Please, Sign In to add comment