You will see the following output: Connecting to the PostgreSQL database. To execute the connect.py file, you use the following command: python connect.py Code language: Shell Session ( shell ) ![]() Finally, close the communication with the database server by calling the close() method of the cursor and connection objects.After that, read the result set by calling the fetchone() method of the cursor object.Then, create a new cursor and execute an SQL statement to get the PostgreSQL database version. ![]() Next, create a new database connection by calling the connect() function.First, read database connection parameters from the database.ini file. ![]() # close the communication with the PostgreSQLĮxcept (Exception, psycopg2.DatabaseError) as error: # display the PostgreSQL database server version Print( 'Connecting to the PostgreSQL database.') #!/usr/bin/python import psycopg2ĭef connect (): """ Connect to the PostgreSQL database server """ The following connect() function connects to the suppliers database and prints out the PostgreSQL database version. Return db Code language: Python ( python ) Raise Exception( 'Section file'.format(section, filename)) The config() function is placed in the config.py file: #!/usr/bin/python from configparser import ConfigParserĭef config (filename= 'database.ini', section= 'postgresql'): # create a parser The following config() function read the database.ini file and returns connection parameters. gitignore file will be like this: database. gitignore file to not committing the sensitive information to the public repo like github. Notice that if you git, you need to add the database.ini to the. Password=SecurePas$1 Code language: Shell Session ( shell )īy using the database.ini, you can change the PostgreSQL connection parameters when you move the code to the production environment without modifying the code. The following shows the contents of the database.ini file: To make it more convenient, you can use a configuration file to store all connection parameters.
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |