Python for .NET Developers 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 the next thing to do is to connect to the database and create the tables. We're going to create a connection string.
0:08 You saw before we were using SQLite, so it's sqlite:///. That would be whatever database connection string
0:14 that you put on, in there. SQLite is just the file. You know, SQL Server, maybe it's like trusted connection equals true, server equals such-and-such.
0:22 Initial catalog equals... you know, whatever it happens to be that goes there. That's the connection string, after this scheme, ///
0:30 Then we create a singleton engine. Going to create that. And then we're going to go to our SQLAlchemyBase
0:36 and we say create all, and we pass it the engine. Now, I mentioned there's a really important thing that we've got to make sure that we import
0:43 all SQLAlchemy derived classes. So all of our entities have to have been imported so by the time we get to this yellow line
0:49 the SQLAlchemy base has seen the fact that it derives from all those things. Remember, Python is not complied.
0:55 The only way it knows about its other files is by importing them. The way we do that, so we just imported
1:00 the guitar.py file, but there's actually a better way if you have a real, true application. So what we can do is that we can create
1:06 this module called all_models.py, and we can just import guitary.data.guitars. Import guitary.data.users. And we've got 20 tables of 20 classes.
1:16 You import them all here, and then down in this you just import that all_models. Why this level of separation?
1:23 Well, it turns out that you have to do this several times in real applications. You might have to do it in this part where we're
1:29 creating the tables, but maybe you're doing migrations like database migrations to keep your database in sync with your classes.
1:36 You also have to do something like that there. So it's easier to put it into this one file you can import and always have this convention.
1:42 I just go back to this one place, all_models, and import a new model that I happen to create. Of course, if you forget it, then you're going to end up
1:50 with, basically, SQLAlchemy not creating those tables because it won't know that they exist.


Talk Python's Mastodon Michael Kennedy's Mastodon