From the course: Advanced SQL for Application Development

Connecting to a database

From the course: Advanced SQL for Application Development

Start my 1-month free trial

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.

Contents