In [11]:
import sqlite3
#create connection that represents the db
conn = sqlite3.connect('example.db')

In [12]:
#create cursor object. Call its execute() method to preform sql queries
c = conn.cursor()

# Create table
c.execute('''CREATE TABLE stocks
             (date text, trans text, symbol text, qty real, price real)''')

# Insert a row of data
c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")

# Save (commit) the changes
conn.commit()

# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
conn.close()

In [13]:
#reopen
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()

In [19]:
# Do this instead of python string manipulation to avoid sql injection problems
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
print(c.fetchone())

# Larger example that inserts many records at a time
purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
             ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
             ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
            ]
c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)


('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14)
Out[19]:
<sqlite3.Cursor at 0x7f00184f57a0>

In [31]:
c.execute('SELECT * FROM stocks')


Out[31]:
<sqlite3.Cursor at 0x7f00184f57a0>

In [32]:
print(c.fetchall())#fetching after executing is a one time thing. Need to execute again


[('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14), ('2006-03-28', 'BUY', 'IBM', 1000.0, 45.0), ('2006-04-05', 'BUY', 'MSFT', 1000.0, 72.0), ('2006-04-06', 'SELL', 'IBM', 500.0, 53.0)]

In [33]:
print(c.fetchone())


None

In [ ]: