1+ """ Simple example of usage of sqlalchemy to illustrate common simple patterns.
2+
3+ Source: http://www.rmunn.com/sqlalchemy-tutorial/tutorial.html
4+ """
5+
6+ from sqlalchemy import *
7+
8+ db = create_engine ('sqlite:///tutorial.db' )
9+
10+ db .echo = False # Try changing this to True and see what happens
11+
12+ # The metadata is a collection of tables that needs to be bound to the
13+ # engine
14+ metadata = MetaData ()
15+ metadata .bind = db
16+
17+ users = Table ('users' , metadata ,
18+ Column ('user_id' , Integer , primary_key = True ),
19+ Column ('name' , String (40 )),
20+ Column ('age' , Integer ),
21+ Column ('password' , String ),
22+ )
23+ users .create ()
24+
25+ i = users .insert ()
26+ i .execute (name = 'Mary' , age = 30 , password = 'secret' )
27+ i .execute ({'name' : 'John' , 'age' : 42 },
28+ {'name' : 'Susan' , 'age' : 57 },
29+ {'name' : 'Carl' , 'age' : 33 })
30+
31+ s = users .select ()
32+ rs = s .execute ()
33+
34+ row = rs .fetchone ()
35+ print 'Id:' , row [0 ]
36+ print 'Name:' , row ['name' ]
37+ print 'Age:' , row .age
38+ print 'Password:' , row [users .c .password ]
39+
40+ for row in rs :
41+ print row .name , 'is' , row .age , 'years old'
0 commit comments