Question 16 MSQ · 3.0 marks
Which of the following is the correct way to connect the Postgresql database using Python?
Published solution
**1. Identify the connection function:** In psycopg2, the public factory for opening a PostgreSQL connection is psycopg2.connect(...). It returns a connection object that can then create cursors.
**2. Match the keyword arguments:** Option B supplies database, user, password, host and port in lowercase. The supplied database is organization, the user is postgres, the server is localhost and its port is 5432.
**3. Separate valid syntax from connection success:** These parameters are the correct call form. A successful actual connection additionally requires a running server, an existing database and valid credentials.
**Answer: B — psycopg2.connect with lowercase database, user, password, host and port.**
A: **Incorrect:** The capitalized connection keywords are not the accepted PostgreSQL parameter names.
B: **Correct:** This uses connect with the correct lowercase connection parameters.
C: **Incorrect:** psycopg2.connection is not the public connect factory; the low-level connection class does not accept this keyword call as a substitute.
D: **Incorrect:** psycopg2 is a module and cannot itself be called as a connection function.