In this lecture, we are going to connect to our database using Python. But first of all, let's make sure that our database is created. And indeed it is. Next let's switch over to the database. So backslash c staff, and the name of the user, me Hi. Okay, we are connected to the database.
Now let's see all the available schemas, backslash d n. And we have our schema right here, my staff for which Mihai is the owner, okay. Now, let me show you the code to connect to the database. So first of all, we should import the necessary module which is psycho PG two, then we are initiating the connection using this variable right here connection equals psycho PG two, so the name of the module, a dot, and then the Connect method. In between the parentheses of the Connect method, we have several arguments that we must define. So we Have database equals staff because this is the name of our database. User equals me high password equals Python.
The host is 127 dot zero dot zero dot one, which is the local host. That's because we have installed Postgres SQL on the local system. And the port to connect to our database is 5432, which is the default port for any PostgreSQL connection. Notice that I have enclosed this code into a try except else code block. That's because we want to try the connection to the database. If any errors occur, then we are catching them using the except clause.
So except psycho PG two dot error as E rr, then we are going to print an error was generated. By the way, I will attach a link to this lecture to psycho PG to documentation to see all the available types of errors and exceptions in this module. Finally, we have else clause, which gets executed in case the code under the try clause generates no exceptions. So in our case, if the connection is successful, then we are printing out this message right here to the screen connection to database was successful. Now let's open up the Python interpreter and execute this code right here. So first we have import psycho PG two.
And then let me copy and paste this try except else block right into the Python interpreter. And after a couple of seconds, we have this message printed out connection to database was successful. So basically, this is the way in which you can connect to a Postgres SQL database using Python. I'll see you in the next lecture.