Suggest a feature
×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Python
Posted by: alphaharris
Added: Oct 18, 2018 4:53 PM
Views: 1
SQLlite Call Without ORM
  1. import sqlite3
  2.  
  3. # We first need to connect to a database
  4. connection = sqlite3.connect('data.db')
  5.  
  6. # The cursor runs queries and stores results
  7. cursor = connection.cursor()
  8.  
  9. create_table = "CREATE TABLE users (id int, username text, password text)"
  10. cursor.execute(create_table)
  11.  
  12. # Form query to insert user
  13. user = (1, 'jose', 'asdf')
  14. insert_query = 'INSERT INTO users VALUES (?, ?, ?)'
  15. cursor.execute(insert_query, user)
  16.  
  17.  
  18. users = [
  19.     (2, 'rolf', 'asdf'),
  20.     (3, 'anne', 'xyz')
  21. ]
  22.  
  23. cursor.executemany(insert_query, users)
  24.  
  25. # Now get data out of the db
  26.  
  27. select_query = 'SELECT * FROM users'
  28. for row in cursor.execute(select_query):
  29.     print(row)
  30.  
  31. connection.commit()
  32.  
  33. connection.close()