Advertisement
UniQuet0p1

Untitled

Apr 16th, 2021
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.58 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3. Following Python code shows how to connect to an existing database.
  4. If the database does not exist, then it will be created and finally
  5. a database object will be returned.
  6. """
  7.  
  8. import sqlite3
  9.  
  10.  
  11. def opendb():
  12. """
  13. open SQLite database
  14. """
  15. global conn
  16. conn = sqlite3.connect('test.db')
  17. print("Opened database successfully")
  18.  
  19.  
  20. def create_table():
  21. # create a table in the previously created database
  22. conn.execute('''CREATE TABLE COMPANY
  23. (ID INT PRIMARY KEY NOT NULL,
  24. NAME TEXT NOT NULL,
  25. AGE INT NOT NULL,
  26. ADDRESS CHAR(50),
  27. SALARY REAL);''')
  28. print("Table created successfully")
  29.  
  30.  
  31. def createRecords():
  32. """
  33. create some records in the COMPANY table
  34. """
  35. conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
  36. VALUES (5, 'Paul', 32, 'California', 20000.00 )");
  37.  
  38. conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
  39. VALUES (6, 'Allen', 25, 'Texas', 15000.00 )");
  40.  
  41. conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
  42. VALUES (7, 'Teddy', 23, 'Norway', 20000.00 )");
  43.  
  44. conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
  45. VALUES (8, 'Mark', 25, 'Rich-Mond ', 65000.00 )");
  46.  
  47. conn.commit()
  48. print("Records created successfully")
  49.  
  50.  
  51. def selectRecords():
  52. """
  53. fetch and display records from the COMPANY table
  54. """
  55. cursor = conn.execute("SELECT id, name, address, salary from COMPANY")
  56. for row in cursor:
  57. print("ID = ", row[0])
  58. print("NAME = ", row[1])
  59. print("ADDRESS = ", row[2])
  60. print("SALARY = ", row[3], "\n")
  61. print("Operation done successfully")
  62.  
  63.  
  64. def delRecords():
  65. """
  66. Delete record where ID = 7 and display records
  67. """
  68. conn.execute("DELETE from COMPANY where ID = 7;")
  69. conn.commit()
  70. print("Total number of rows deleted :", conn.total_changes)
  71.  
  72. cursor = conn.execute("SELECT id, name, address, salary from COMPANY")
  73. for row in cursor:
  74. print("ID = ", row[0])
  75. print("NAME = ", row[1])
  76. print("ADDRESS = ", row[2])
  77. print("SALARY = ", row[3], "\n")
  78.  
  79. print("Operation done successfully")
  80.  
  81.  
  82. def closeconn():
  83. """
  84. close connection
  85. """
  86. conn.close()
  87. print("Connection closed")
  88.  
  89.  
  90. if __name__ == "__main__":
  91. opendb()
  92. # create_table()
  93. # createRecords()
  94. # selectRecords()
  95. delRecords()
  96. closeconn()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement