Posted By

GabrielTheodoulos on 07/20/16


Tagged

data Reading SQLite


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

BigD3m0n


Reading Data from sqlite Table


 / Published in: Python
 

URL: https://www.youtube.com/watch?v=o-vsdfCBpsU

This shows several examples on how to read data from a sqlite table.

  1. import sqlite3
  2.  
  3. conn = sqlite3.connect('tutorial.db') # Don't forget to connect to db!
  4. c = conn.cursor() # think of it like a mouse cursor
  5.  
  6.  
  7. # def create_table():
  8. # c.execute("CREATE TABLE example(Language VARCHAR, Version REAL, Skill TEXT)")
  9. #
  10. #
  11. # def enter_data():
  12. # c.execute("INSERT INTO example VALUES('Python', 2.7, 'Beginner')")
  13. # c.execute("INSERT INTO example VALUES('Python', 3.3, 'Intermediate')")
  14. # c.execute("INSERT INTO example VALUES('Python', 3.4, 'Expert')")
  15. # conn.commit() # Instead of closing the db every time you enter data,
  16. # # and then reopen it, you run .commit() to update the db table with your data
  17. #
  18. #
  19. # def enter_dynamic_data():
  20. # lang = input("What language?: ")
  21. # version = float(input("What version?: "))
  22. # skill = input("What skill level?: ")
  23. #
  24. # c.execute("INSERT INTO example (Language, Version, Skill) VALUES (?, ?, ?) ", (lang, version, skill))
  25. # # This is the actual interface of the input data, placing it into the db.
  26. #
  27. # conn.commit()
  28.  
  29.  
  30. def read_from_database():
  31. # Example 1: Universal Print All
  32. sql = "SELECT * FROM example"
  33. for row in c.execute(sql):
  34. print(row)
  35.  
  36. # Example 2: Print only WHERE Skill == 'Beginner'
  37. sql = "SELECT * FROM example WHERE Skill == 'Beginner'"
  38. for row in c.execute(sql):
  39. print(row)
  40.  
  41. # Example 3: Print User Input Choice of Skill
  42. what_skill = input("What skill are you looking for?: ")
  43. sql = "SELECT * FROM example WHERE Skill = ?"
  44. for row in c.execute(sql, [(what_skill)]):
  45. print(row)
  46.  
  47. # Example 4: Print User Input Multiple Choices of Skill and Language
  48. what_skill = input("What skill are you looking for?: ")
  49. what_lang = input("What language?: ")
  50. sql = "SELECT * FROM example WHERE Skill = ? AND Language = ?"
  51. for row in c.execute(sql, [(what_skill), (what_lang)]):
  52. print(row)
  53.  
  54.  
  55. # create_table() # Only needs to be run once! More than once creates an error.
  56. # enter_data() # Runs the function enter_data()
  57. # enter_dynamic_data()
  58. read_from_database()
  59.  
  60. conn.close() # this is only needed at the very end of the program. Use the .commit() instead.

Report this snippet  

You need to login to post a comment.