Wednesday, October 19, 2011

web2py: how to connect existing tables


Tested environment:
mssql 2008

DAL
You need to make sure you disable Migration otherwise it might alter your tables. I recommend to specify at connection level (not each table) so that you don't forget.

db = DAL("mssql2://YourID:YourPassword@YourServer/YourDB", migrate=False)

If table has Primary field called id
You're lucky. This meet with the convention of web2py


You can connect with the following.
db.define_table('table1',
    Field('name'))
If table has primary key field called ID
Shoot, it's a capital letter... don't worry the code above will still work !

If table has primary key field called myid
Why didn't I name the field carefully.... no problem. You can still connect.
Since it's not field called id/ID, you need to define your primary field just like others and set primarykey for it.
db.define_table('table1',
    Field('myid'),
    Field('name'),
    primarykey=['myid'])
If table has No primary key field
What's wrong with me ? ... don't worry here's what I found. You know what, the above code still works !





5 comments:

  1. Per Anthony, it's better to use migrate_enable=False.

    migrate_enable=False
    Disable the migratoin

    migrate=False
    Set the default to tables but migration can be enabled.


    db = DAL("mssql2://YourID:YourPassword@YourServer/YourDB", migrate_enabled=False)

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. but the fields that use primary key composed? How they look?
    Sorry per translations errors.

    ReplyDelete
  4. but the fields that use primary key composed? How they look?
    Sorry per translations errors.

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete