def load_by_parameter(brand): with sqlite3.connect(Database) as conn: conn.text_factory = str # by default, it will return unicode, so change it to 'str' # ? placeholder # the real parameter expects a tuple or list, so we have to wrap it # into tuple # even there is just only one element cursor = conn.execute("SELECT Id,Brand,Model,Price FROM Cars WHERE Brand=?",(brand,)) Car.display(cursor2cars(cursor)) # named placeholder cursor = conn.execute("SELECT COUNT(*) AS Count,AVG(Price) FROM Cars WHERE Brand=:brand",{"brand":brand}) # we know the result is only one row, so we can call fetchone() row = cursor.fetchone() print "'{brand}' has {total} cars, average price is {avgprice:.3f}".format(brand=brand,total=row[0],avgprice=row[1])
def load_access_col_by_name(): """ to access each column in row by name instead of index we need to set connection's row_factory to 'sqlite3.Row' """ with sqlite3.connect(Database) as conn: conn.text_factory = str # by default, it will return unicode, so change it to 'str' conn.row_factory = sqlite3.Row cursor = conn.execute("SELECT * FROM Cars") cars = [] for row in cursor: c = Car(brand=row["Brand"],price=row["Price"],model=row["Model"]) c.id = row["Id"] cars.append(c) Car.display(cars)
def load_access_col_by_name(): """ to access each column in row by name instead of index we need to set connection's row_factory to 'sqlite3.Row' """ with sqlite3.connect(Database) as conn: conn.text_factory = str # by default, it will return unicode, so change it to 'str' conn.row_factory = sqlite3.Row cursor = conn.execute("SELECT * FROM Cars") cars = [] for row in cursor: c = Car(brand=row["Brand"], price=row["Price"], model=row["Model"]) c.id = row["Id"] cars.append(c) Car.display(cars)
def load_by_parameter(brand): with sqlite3.connect(Database) as conn: conn.text_factory = str # by default, it will return unicode, so change it to 'str' # ? placeholder # the real parameter expects a tuple or list, so we have to wrap it # into tuple # even there is just only one element cursor = conn.execute( "SELECT Id,Brand,Model,Price FROM Cars WHERE Brand=?", (brand, )) Car.display(cursor2cars(cursor)) # named placeholder cursor = conn.execute( "SELECT COUNT(*) AS Count,AVG(Price) FROM Cars WHERE Brand=:brand", {"brand": brand}) # we know the result is only one row, so we can call fetchone() row = cursor.fetchone() print "'{brand}' has {total} cars, average price is {avgprice:.3f}".format( brand=brand, total=row[0], avgprice=row[1])
def load_basic(): with sqlite3.connect(Database) as conn: conn.text_factory = str # by default, it will return unicode, so change it to 'str' cursor = conn.execute("SELECT Id,Brand,Model,Price FROM Cars ORDER BY PRICE") Car.display(cursor2cars(cursor))
def load_basic(): with sqlite3.connect(Database) as conn: conn.text_factory = str # by default, it will return unicode, so change it to 'str' cursor = conn.execute( "SELECT Id,Brand,Model,Price FROM Cars ORDER BY PRICE") Car.display(cursor2cars(cursor))