Python for the .NET developer Transcripts
Chapter: Database access and ORMs in Python
Lecture: Concept: Creating the tables

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Once we have our entities defined
0:02 the next thing to do is to connect to the database
0:04 and create the tables.
0:06 We're going to create a connection string.
0:07 You saw before we were using SQLite, so it's sqlite:///.
0:11 That would be whatever database connection string
0:13 that you put on, in there. SQLite is just the file.
0:16 You know, SQL Server, maybe it's like
0:19 trusted connection equals true, server equals such-and-such.
0:21 Initial catalog equals... you know, whatever it happens
0:24 to be that goes there.
0:25 That's the connection string, after this scheme, ///
0:29 Then we create a singleton engine. Going to create that.
0:32 And then we're going to go to our SQLAlchemyBase
0:35 and we say create all, and we pass it the engine.
0:38 Now, I mentioned there's a really important thing
0:40 that we've got to make sure that we import
0:42 all SQLAlchemy derived classes.
0:44 So all of our entities have to have been imported
0:46 so by the time we get to this yellow line
0:48 the SQLAlchemy base has seen the fact
0:51 that it derives from all those things.
0:52 Remember, Python is not complied.
0:54 The only way it knows about its other files
0:56 is by importing them.
0:57 The way we do that, so we just imported
0:59 the file, but there's actually a better way
1:01 if you have a real, true application.
1:04 So what we can do is that we can create
1:05 this module called, and we can just import
1:09 Import
1:12 And we've got 20 tables of 20 classes.
1:15 You import them all here, and then down in this
1:18 you just import that all_models.
1:20 Why this level of separation?
1:22 Well, it turns out that you have to do this several times
1:25 in real applications.
1:26 You might have to do it in this part where we're
1:28 creating the tables, but maybe you're doing migrations
1:30 like database migrations to keep your database
1:33 in sync with your classes.
1:35 You also have to do something like that there.
1:37 So it's easier to put it into this one file
1:39 you can import and always have this convention.
1:41 I just go back to this one place, all_models, and import
1:44 a new model that I happen to create.
1:46 Of course, if you forget it, then you're going to end up
1:49 with, basically, SQLAlchemy not creating those tables
1:52 because it won't know that they exist.