Python Psycopg – Connection class
The connection to a PostgreSQL database instance is managed by the connection class. It’s more like a container for a database session. The function connect() is used to create connections to the database. The connect() function starts a new database session and returns a connection class instance. We can construct a new cursor to perform any SQL statements by putting the connection object to use.
psycopg2.connect(database=”dbname”, user=’postgres’, password=passwords, host=local_host, port= port_number)
- dbname =the database name
- user =user name used to authenticate (widely used= postgres)
- password= password
- host =database host address
- port =connection port number (defaults = 5432 )
We import the psycopg package. conn is the connection variable that contains the connection for the “Classroom database”, where the user is ‘Postgres’, the password is ‘pass’, the local host is ‘127.0.0.1’ and the port number is ‘5432’.
Methods in Connection Class
- cursor(): The connection is what creates cursors. They are permanently connected to the connection, and all instructions are run in the context of the database session are covered by the connection.
cursor(name=None, cursor_factory=None, scrollable=None, withhold=False)
- name: by default “none”, if the name is given a server-side cursor will be returned, if none is given a regular client-side server will be returned.
- cursor_factory: to create non-standard cursors
- scrollable: default None
- withhold: default False
- commit(): commit() is a method for committing data. This method commits the current transaction by sending a “COMMIT” statement to the Postgresql server. Because Python does not auto-commit by default, calling this method after each transaction that alters data for tables is necessary.
- rollback(): It helps us return to the beginning of any pending transaction. Closing a connection without first committing or saving the modifications will result in an implicit rollback.
- close(): This method is used to close the connection to the database.
In the below example, The create table command is executed and values are inserted into the table using the insert SQL command. The changes are saved using the commit() method. Finally, the connection to the database is closed using the close() method.
Table successfully created (12891, 'rachel', Decimal('9.5')) (12892, 'ross', Decimal('8.93')) (12893, 'nick', Decimal('9.2'))
Please Login to comment...