Advertisement
jw910731

Python Sqlite test

Mar 23rd, 2021
506
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 KB | None | 0 0
  1. import sqlite3
  2.  
  3.  
  4. # query if table exist
  5. def table_exist(conn, table_name):
  6.     cur = conn.cursor()
  7.     result = list(cur.execute(
  8.         "SELECT name FROM sqlite_master WHERE type='table' AND name='%s';" % table_name))
  9.     return len(result) > 0
  10.  
  11.  
  12. class Customer():
  13.     def __init__(self, name, gender, birthday):
  14.         self.name = name
  15.         self.gender = gender
  16.         self.birthday = birthday
  17.  
  18.  
  19. # Create customer record in DB
  20. # @return created record unique id
  21. def insert_customer(conn, customer):
  22.     cur = conn.cursor()
  23.     cur.execute(
  24.         "INSERT INTO customer (name, gender, birthday) VALUES (:name, :gender, :birthday)", customer.__dict__)
  25.     return cur.lastrowid
  26.  
  27.  
  28. def main():
  29.     conn = sqlite3.connect('test.db')
  30.     if not table_exist(conn, "customer"):
  31.         # Create DB table if table not exist
  32.         cur = conn.cursor()
  33.         cur.executescript("""
  34.            CREATE TABLE customer(
  35.                rowid INTEGER PRIMARY KEY AUTOINCREMENT,
  36.                name TEXT NOT NULL,
  37.                gender INTEGER NOT NULL,
  38.                birthday DATE NOT NULL
  39.            );
  40.        """)
  41.     customer = Customer(input("Input Customer Name: "), int(input(
  42.         "Input Customer Gender (1 = male, 2 = female): ")), input("Input Customer Birthday (in YYYY-MM-DD format): "))
  43.     insert_customer(conn, customer)
  44.     conn.commit()
  45.     conn.close()
  46.  
  47.  
  48. if __name__ == "__main__":
  49.     main()
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement