# 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-03-27','BUY','RHAT',100,60.14))
# 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), ('2006-04-07', 'SELL', 'MSFT', 500, 74.00), ('2006-04-08', 'SELL', 'IBM', 500, 54.00), ('2006-04-09', 'SELL', 'MSFT', 500, 73.00), ('2006-04-10', 'SELL', 'MSFT', 500, 75.00), ('2006-04-12', 'SELL', 'IBM', 500, 55.00), ] c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)
# Save (commit) the changes con.commit()
# Do this instead t = ('RHAT',) c.execute('SELECT * FROM stocks WHERE symbol=?', t) #print(c.fetchone())
#for row in c.execute('SELECT * FROM stocks ORDER BY price'): # print(row) #for row in c.execute('SELECT * FROM stocks LIMIT 5 OFFSET 0'): # print(row) for row in c.execute('SELECT * FROM stocks LIMIT 5 OFFSET 1'): print(row) #Select Top N * From
# Create table c.execute('''CREATE TABLE COMPANY (ID integer, NAME text, AGE integer, ADDRESS text, SALARY real)''')
# Larger example that inserts many records at a time purchases = [(1,'Paul',32,'California',20000.0), (2,'Allen',25,'Texas',15000.0), (3,'Teddy',23,'Norway',20000.0), (4,'Mark',25,'Rich-Mond',65000.0), (5,'David',27,'Texas',85000.0), (6,'Kim',22,'South-Hall',45000.0), (7,'James',24,'Houston',10000.0)] c.executemany('INSERT INTO COMPANY VALUES (?,?,?,?,?)', purchases)
# Save (commit) the changes con.commit()
# 返回数据库表最后 n 行记录 # 先计算一个数据库表中的行数 c.execute("SELECT count(*) FROM COMPANY;") last = c.fetchone()[0] n = 5 c.execute("SELECT * FROM COMPANY LIMIT ? OFFSET ?;", (n, last-n)) for row in c: print(row)
# 计算一个数据库表中的行数 c.execute("SELECT count(*) FROM COMPANY;") print(c.fetchone())
# 选择某列的最大值 c.execute("SELECT max(salary) FROM COMPANY;") print(c.fetchone())
# 选择某列的最小值 c.execute("SELECT min(salary) FROM COMPANY;") print(c.fetchone())
# 计算某列的平均值 c.execute("SELECT avg(salary) FROM COMPANY;") print(c.fetchone())
# 为一个数值列计算总和 c.execute("SELECT sum(salary) FROM COMPANY;") print(c.fetchone())