![]() ![]() In essence: we try to connect to the database and run queries when there are no OperationalError exceptions. If an OperationalError exception is raised during the connection process, the except block is triggered, and we get notified that there was an error connecting to the database.If the try block succeeds, the connect() function returns a database connection instance, db_connection. ![]() Let’s parse what the above code snippet does. connect( **db_info) print( "Successfully connected to the database.") except OperationalError: print( "Error connecting to the database :/") # psycopg2-tutorial/main.py import psycopg2 from psycopg2 import OperationalError from db_config import get_db_info filename = 'db_info.ini' section = 'postgres-sample-db' db_info = get_db_info(filename,section) try: db_connection = psycopg2. Now, let’s import the OperationalError class from psycopg2 and handle the OperationalError exception using Python’s try and except blocks. Therefore, such connection errors that arise due to incorrect or invalid values can all be subsumed under the OperationalError exception. And you’ll see that an OperationalError exception is thrown in all of the runs. You can run the script a few more times by changing one or more fields to invalid values. Port 5432 failed: FATAL: database "test1" does not exist It’s an OperationalError exception (again). What happens when you try connecting to a database that does not exist? For example, I updated the dbname field in the config file from test to test1 (the test1 database does not exist). Port 5432 failed: FATAL: password authentication failed for user "postgres" Psycopg2.OperationalError: connection to server at "localhost" (::1), \ Psycopg2 has an implementation of the OperationalError class. Focusing on the relevant information in the traceback, you’ll see that an OperationalError exception is thrown as password authentication failed. Open the config file db_info.ini, update the password to something invalid, and run the script again. Suppose you enter an incorrect password (yeah, that happens often!). However, we haven’t accounted for the errors that may arise during the connection process. We stored the details of the database in a config file, parsed it using ConfigParser, and connected to the database using the connect() function from psycopg2. connect( **db_info) print( "Successfully connected to the database.") Handling Connection Errors # psycopg2-tutorial/main.py import psycopg2 from db_config import get_db_info filename = 'db_info.ini' section = 'postgres-sample-db' db_info = get_db_info(filename,section) db_connection = psycopg2. The configparser module, built into the Python standard library, lets you parse configuration files of the INI file format. So you should always store the credentials in a config file or set them as environment variables whose values you can fetch as needed. In such cases, if the database credentials change, you can only modify the contents of the config file without introducing breaking changes elsewhere.Īlso, exposing sensitive info like passwords in source code is a security risk. You can then parse the config file, retrieve the required details, and use them in the call to the connect() function.īut why is this helpful? When working on a project, you may need to connect to multiple databases or connect to a database from more than one module. In practice, you should store the details of the database and the credentials required to connect to it in a config file. ? Specifying the details of the database in the function call, as shown above, is a good example of how not to connect to a database. ![]() ![]() You can use the connect() function as shown: It returns a connection object if the connection succeeds. The connect() function takes in the information needed to connect to the database, such as the name of the database, username, and password, as keyword arguments. To connect to a database, you can use the connect() function from psycopg2. As a first step, let’s create a main.py file, import psycopg2, and connect to a PostgreSQL database. The connect() Function in Psycopg2Īfter you’ve installed the psycopg2 library, you can import it into your working environment. You can optionally specify the username, host, and port else, is created with the default values for these fields. If you use psql at the command line, check if you have the right permissions, and run CREATE DATABASE. You can create a database on pgAdmin or use the command-line client psql. You have a database that you can connect to.Ensure that your PostgreSQL database server is up and running, and. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |