import sqlite3
# hypothetical book sales data
book_data = [('12-1-2020', 'Practical Data Science With Python', 19.99, 1),
('12-15-2020', 'Python Machine Learning', 27.99, 1),
('12-17-2020', 'Machine Learning For Algorithmic Trading', 34.99, 1)]
# CREATE and INSERT
connection = sqlite3.connect('book_sales.db')
cursor = connection.cursor()
# Create table
cursor.execute('''CREATE TABLE book_sales
(date text, book_title text, price real, quantity real)''')
# the table is now there
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
cursor.fetchall()
# Insert a row of data
cursor.execute("INSERT INTO book_sales VALUES (?, ?, ?, ?)", book_data[0])
cursor.execute('SELECT * FROM book_sales ;')
cursor.fetchall()
# Save the changes with .commit()
# Without this line, the inserted data will not be saved in the database after we close the connection
connection.commit()
# insert several records at a time
cursor.executemany('INSERT INTO book_sales VALUES (?, ?, ?, ?)', book_data[1:])
# don't forget to save the changes
connection.commit()
cursor.execute('SELECT * FROM book_sales ;')
cursor.fetchall()
connection.close()
from sqlalchemy import create_engine
engine = create_engine("sqlite:///book_sales.db")
connection = engine.connect()
result = connection.execute("select * from book_sales")
result
list(result)
for row in result:
print(row['data'])
result = connection.execute("select * from book_sales")
for row in result:
print(row['date'])
with engine.connect() as connection:
result = connection.execute("select * from book_sales")
for row in result:
print(row)
connection.close()
No comments:
Post a Comment