Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. import os
  2. import sqlite3
  3.  
  4. def create_tables(conn):
  5. conn.execute("CREATE TABLE contacts (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, email TEXT)")
  6. conn.commit()
  7.  
  8. def connect(path="contacts.db", syncdb=False):
  9. """
  10. Connects to the database and ensures there are tables.
  11. """
  12. if not os.path.exists(path):
  13. syncdb=True
  14.  
  15. conn = sqlite3.connect(path)
  16. if syncdb:
  17. create_tables(conn)
  18.  
  19. return conn
  20.  
  21. def insert(name, email, conn=None):
  22. if not conn: conn = connect()
  23.  
  24. sql = "INSERT INTO contacts (name, email) VALUES (?, ?)"
  25. conn.execute(sql, (name, email))
  26. conn.commit()
  27.  
  28. if __name__ == "__main__":
  29. name = raw_input("Enter name: ")
  30. email = raw_input("Enter email: ")
  31. conn = connect()
  32. insert(name, email, conn)
  33.  
  34. contacts = conn.execute("SELECT count(id) FROM contacts").fetchone()[0]
  35. print "There are now %i contacts" % contacts
  36.  
  37. conn.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement