From the course: Advanced SQL for Application Development
Connecting to a database
From the course: Advanced SQL for Application Development
Connecting to a database
- [Narrator] Our next step that we're going to go over is how to connect to the database. Now, offscreen I reset the password in the environment variable to the actual password, but the username hasn't changed, so I'll just show that again. So user and let's look at the length of the password. Just so you know it is actually set. And you'll see I have a 10 character password on that. Now the next step is to create a connection. A connection is basically a data structure which allows us to communicate with the database backend from our application. Now, to do that in Python, we specify the variable name. Typically "C-O-N-N" is a good generic variable name. And we specify the Python library for connecting which is "P-S-Y-C-O-P-G-2", and we call the connect function. The connect function's going to return a connection. And we simply have to specify a database. And the name of our database is "E-C-O-M-M". And our username is actually stored in our variable user, and our password, which we retrieved from the environment variable, is stored in a variable called password. And we need to specify a port. We're going to use the default postgres port 5433. That will look on port 5433 on the localhost. When we hit return, we now have created a variable called "C-O-N-N". So let's take a look at that. You'll notice it's a connection object. And you'll notice here it has some of the same information that we passed in. The username is postgres, the password is blanked out, our database name is ecomm, and we're working with the default port 5433. Now, once we have a connection, then we want to be able to use something called a cursor. A cursor is created on a connection. A cursor is like a logical pointer to the results of a query. We can create a cursor and call it cursor. We're going to create that on the connection, and we're going to create it by calling the cursor function. Now, let's take a look at the cursor object or the cursor variable. We'll notice, again, this is an object. We're going to be manipulating cursors and to some degree, connections in the following videos as we execute queries and do some manipulation with our data.
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.
Contents
-
-
-
(Locked)
Designing an ecommerce application database6m 5s
-
(Locked)
Creating tables and loading data4m 12s
-
(Locked)
Using environment variables for connection parameters3m 57s
-
Connecting to a database2m 28s
-
(Locked)
Parameterizing SELECT statements3m 37s
-
(Locked)
Avoiding N+1 queries7m 18s
-
(Locked)
Challenge: Write a parameterized query in Python43s
-
(Locked)
Solution: How to write a parameterized query in Python2m 21s
-
(Locked)
-
-
-
-
-
-