SQLAlchemy

Just like SQLObject

Third party library “Object relational manager”
Define database tables, connect (map) classes to tables Table rows are objects / instances What you do to an object, you do to a row

Phrase queries in a more “pythonic” (less SQL-ish) way Hide database differences The database disappears ...

Making an engine Connecting is slightly more complicated than SQLObject: Use a connection string of the form driver://username:password@host:port/database Make a “database engine” with create_engine encoding and convert_unicode can be used to convert characters for all transactions echo can be set to print raw SQL Use to make special metadata object from sqlalchemy import * conn_str = "mysql://dbuser:dbpass@localhost:8028/epi" engine = create_engine (conn_str. echo=True) metadata = MetaData (engine) .

Don’t forget to close() it! Actually we don’t need to use the connection .execute ("SELECT * FROM reports") # returns a sequence of dictionaries for row in result: print row[’id’].Making a connection Call connect from engine Connection can execute raw SQL.close() ... like DB-API cursor objects. row[’country’] connection.connect() result = connection. connection = engine.

Date()). defines the corresponding table. String(32). Column (’locn_lon’. Column (’country’. Column (’locn_lat’. String(64). Column (’date_collected’. nullable=False). The general form is Table (<name>.Define tables Instantiating a Table object (not defining a class). default=EXACT). Float()). ) SampleTable.create() . metadata. <metadata>. primary_key=True). Float()). [<column definition>]+) Metadata binds table to database SampleTable = Table (’sample’. Column (’ident’. String(32). Column (’locn_method’.

Links to actual database via metadata. Can create all bound tables with <metadata>.Table options Defining table is a call. Create table via <class>.create all(). .create(). Can take autoload parameter to work out columns from database.

1) # .1.execute (ident=’X47’.The awkward way of using the database Require a call on the table then an explicit execution query = SampleTable. locn_lat=34.execute ( ’ident’=’X47’. locn_lon=-12.insert() query.1) .. or . locn_lon=-12. query = SampleTable....insert(). locn_lat=34.1.

the field width is variable (Text) UnicodeCol A per StringCol. but with unicode strings. with a level of precision. FloatCol (precision) A float. Boolean May be implemented as a variety of types. . Numeric (precision. DateTime Also see Date and Time. Integer Duh. If length isn’t given. length) Precise float with the given overall width and number of figures after the point.Columns Oddly familiar: String (length) A string.

Opposite to SQLObject. oninsert Default value when entry created and no value supplied. .. Will call if callable. If no default. default Default value for column. nullable True Value for this column. onupdate Default value when entry updated and no value supplied.. Can be callable. must be provided (like NOT NULL). when created.Column parameters primarykey False Is it a unique id for the row? You can have as many as you want .

where a source must be provided. primarykey=True ) Column (’source’. DateTime(). Column(’time_updated’.Column example A timestamped table for samples.now()). and a user-provided string serves as an id TimedTable = Table (’sample’. metadata. nullable=False) Column (’time_created’. onupdate=func. String(30). Column (’ident’. ) . DateTime().now()). String(10). default=func.

metadata. autoload=True) emails = Table(’emails’. autoload=True) .Autoload tables Derive columns from database users = Table(’users’. metadata.

max (mylist) Wraps max for later calling max (mylist).substr (users.c.name. func.now () Wraps “now() for later calling.c.substr (2. 1) Wraps for later call users.func An answer to delayed execution / calling of functions: it binds a function and can later call it with passed parameters. 2.name. 1) . func. “ func.

users) ...) class User (object): pass usermapper = mapper (User. Instead they are mapped. users = Table (’user_table’. .Mappers Objects (in Python) don’t automatically map to database tables and rows.

lon): self. mapper (<class>. lat.lat = lat self. <table object>) You can use __init__ and subclass mapped objects Interaction takes place in the context of a session class Report (object): def init (self): # . def setLocn (self.Mapped classes Any mapped classes get the columns of the table as members for free.. Mapped classes must be derived from object.lon = lon ..

save (changed_objs) # saves everything sess....flush() . bind_to parameter is optional. much later .Sessions Sessions are devices for caching and saving the changes in objects in tables. sess = create_session (bind_to=engine) # . List the objects to be saved. sess..

>>> results = query.select () >>> str (query) SELECT * FROM report .q.select select method of table searches rows query = <table-class>.execute() .select ([<class>.execute() select_by() >>> query = report_table..field == <val>]+) query..

execute() >>> first_row = results.Results Query results are sequences of dictionary-like objects Results are “lazy” and can be sliced Use fetch syntax Can (should) close results >>> results = query.id ’X47’ >>> second_row = results[1] >>> results.close() .fetchone() >>> first_row[’id’] ’X47’ >>> first_row.

country.select (report_table.c.select ([report_table.country]) country_query = report_table. ’South Korea’)) .id. report_table.Select options Use special c attribute to express clauses and conditions Can specify columns to return in select Can test fields some_cols_query = report_table.c.in_ ( ’North Korea’.c.country==’Burma’) next_query = report_table.select (report_table.c.

select operators ==. and |) +. -. etc. &. >. and .startswith(). . and_() and or_() (or ~.between(). / .endswith() . . *. >=. .in_() not_().like().

query = report_table.c.country == ’Burma’).Multiple selectors Use and_. ). op_ & not to combine conditions. (Report.country == ’Myanmar’).diseaseStatus == None).c. ) .c.select (and_ ( (Report. or_ ( (Report.

country.substr ( report_table.Using func in select Can use func to make arbitrary tests of fields. report_table.execute() . 1) == ’A’).select (func.c.

1) == ’A’).Select via mapped classes You can select classes instead of tables.filter (Report.select (func.query (Report) reps = query.country == ’Burma’) .execute() query = session.c.c.country. report_table. Make queries on session and filter.substr ( Report.

Odds and ends orm.clear_mappers(): clears all class mappings. useful during development Allegedly slow Have to explicitly manage sessions Many ways to do things (like SQLObject) .

MySQL tools Graphical tools for administering MySQL. maybe the best) iSQL (cross platform) .these are only based on my personal experience. Aqua Data Studio ($?) CocoaMySQL (OSX. There are many .

Resources SQLAlchemy SQLAlchemy tutorial SQLAlchemy talk slides .

Sign up to vote on this title
UsefulNot useful